Hi
I have below query and i am getting error - Aggregate function not allowed
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
Muhammad Imran AnsariPosted Jan 28, 2025, 4:14 PM
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:
Jaish MathewsPosted Jan 28, 2025, 7:54 AM
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:
Key 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.Amit MohantyPosted Jan 28, 2025, 6:45 AM
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: