Skip to content
Advertisement

SQL – An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause

If you see the picture below, I only want to see those categories where the average revenue is greater than the overall average.

enter image description here

The query that I’m using is below. The very last line is causing the issue.

WITH cte_avg AS (
    SELECT P.prod_cat, Avg_revenue = AVG(CAST(T.total_amt AS NUMERIC))
    FROM [dbo].[Transactions] AS T
    LEFT JOIN [dbo].[prod_cat_info] AS P ON T.prod_cat_code=P.prod_cat_code
    GROUP BY P.prod_cat
)
SELECT prod_cat, Avg_revenue
FROM cte_avg
WHERE Avg_revenue > AVG(Avg_revenue)

The error that I’m getting is:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Please let me know how I can fix this. Thanks!

Advertisement

Answer

I think the query you want to write is something like:

select p.prod_cat, t.avg_total_amount
from (
    select prod_cat_code, avg(total_amount) as avg_total_amount
    from transactions
    group by prod_cat_code
    having avg(total_amount) > (select avg(total_amount) from transactions)
) t
inner join prod_cat_info p on p.prod_cat_code = t.prod_cat_code

The subquery aggregates transactions by category, compute the average, and compares it against the overall transaction average. Then we just bring the categories table with a join.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement