diff --git a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/JdbcEnrollmentAnalyticsManager.java b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/JdbcEnrollmentAnalyticsManager.java index 41d686faa31..09adfaf515f 100644 --- a/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/JdbcEnrollmentAnalyticsManager.java +++ b/dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/JdbcEnrollmentAnalyticsManager.java @@ -542,12 +542,19 @@ private String addCteFiltersToWhereClause(EventQueryParams params, CTEContext ct } } } + // Handle the row context case List rowContextColumns = RowContextUtils.getRowContextWhereClauses(cteContext); - if (!StringUtils.isEmpty(whereClause)) { - whereClause.append(" AND "); + if (rowContextColumns.isEmpty()) { + return whereClause.toString(); + } else { + if (whereClause.isEmpty()) { + whereClause.append(" where "); + } else { + whereClause.append(" AND "); + } + whereClause.append(String.join(" AND ", rowContextColumns)); } - whereClause.append(String.join(" AND ", rowContextColumns)); return whereClause.toString(); } @@ -1041,14 +1048,14 @@ private CTEContext getCteDefinitions(EventQueryParams params) { String cteSql = """ -- Generate CTE for program stage items - SELECT DISTINCT ON (enrollment) enrollment, %s as value, %s + SELECT DISTINCT ON (enrollment) enrollment, %s as value%s FROM %s WHERE eventstatus != 'SCHEDULE' AND ps = '%s' ORDER BY enrollment, occurreddate DESC, created DESC""" .formatted( colName, - rowContextAllowedAndNeeded(params, queryItem) ? "true as exists_flag" : "", + rowContextAllowedAndNeeded(params, queryItem) ? " ,true as exists_flag" : "", eventTableName, queryItem.getProgramStage().getUid());