Hi
I have below query and i am getting error - Aggregate function not allowed
SQL
SELECT T1."TransId", Max(T1."RefDate") FROM OJDT T0 INNER JOIN JDT1 T1 ON T0."TransId" = T1."TransId" WHERE (Select Count(T1."BPLId") from JDT1 A1 where A1."TransId" = T1."TransId") > 0
group By T1."TransId"Thanks

Amit MohantyRank #112 · 20K reputationPosted Jan 28, 2025, 1:45 AM EST
You are getting the error because you are trying to use an aggregate function (Max) alongside a subquery within the WHERE clause. SQL Server does not allow mixing aggregate functions with certain types of subqueries. Once try the below query:
SELECT T1."TransId", MAX(T1."RefDate") AS MaxRefDate FROM OJDT T0 INNER JOIN JDT1 T1 ON T0."TransId" = T1."TransId" WHERE T1."TransId" IN ( SELECT A1."TransId" FROM JDT1 A1 WHERE A1."BPLId" IS NOT NULL GROUP BY A1."TransId" HAVING COUNT(A1."BPLId") > 0 ) GROUP BY T1."TransId";Jaish MathewsRank #225 · 11K reputationPosted Jan 28, 2025, 2:54 AM EST
The error occurs because of the aggregate function usage in a
WHEREclause. SQL does not allow aggregate functions (likeCOUNT()) directly in theWHEREclause. Instead, you need to use a HAVING clause for such conditions, as it is evaluated after grouping.Here’s the corrected query:
SELECT T1."TransId", MAX(T1."RefDate") AS "MaxRefDate" FROM OJDT T0 INNER JOIN JDT1 T1 ON T0."TransId" = T1."TransId" GROUP BY T1."TransId" HAVING (SELECT COUNT(A1."BPLId") FROM JDT1 A1 WHERE A1."TransId" = T1."TransId") > 0Key Changes:
Aggregate in
HAVING: The subquery(SELECT COUNT(A1."BPLId")...)is now placed in theHAVINGclause, as it applies to the grouped result.MAXfunction: TheMAX(T1."RefDate")works fine in theSELECTstatement as it aligns with theGROUP BY.Explanation:
GROUP BY T1."TransId"ensures eachTransIdis processed as a group.MAX(T1."RefDate")retrieves the maximumRefDatefor each group.HAVINGclause filters out groups where the subquery’sCOUNTresult is not greater than 0.Notes:
(COUNT(A1."BPLId"))could be calculated as part of the main query, consider optimizing the query by joining the necessary tables rather than using a subquery.Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 28, 2025, 11:14 AM EST
Hi Ramco,
In your subquery, you are using directly Count() but SQL Server does not allow the use of an aggregate function (e.g., COUNT()) within a WHERE clause. To fix this issue, you need to refactor the query to use CTE. Using CTE, you can enhance the readability and separates filtering logic. Here is the query:
WITH FilteredTransIds AS ( SELECT A1."TransId" FROM JDT1 A1 GROUP BY A1."TransId" HAVING COUNT(A1."BPLId") > 0 ) SELECT T1."TransId", MAX(T1."RefDate") AS "MaxRefDate" FROM OJDT T0 INNER JOIN JDT1 T1 ON T0."TransId" = T1."TransId" WHERE T1."TransId" IN (SELECT "TransId" FROM FilteredTransIds) GROUP BY T1."TransId"