sqlsql-servert-sqlhaving

'invalid column name' while using the HAVING


I am using Microsoft SQL Server 2014.

The following is my query

SELECT type, SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
HAVING total_calories > 150;

and I get the error

Msg 207, Level 16, State 1, Line 2 Invalid column name 'total_calories'.

Can somebody point out what am I doing wrong? Thanks.


Solution

  • Aggregation is required , as you have no access to alias total_calories

    SELECT   type,SUM(calories) AS total_calories 
    FROM     exercise_logs 
    GROUP BY type 
    HAVING   SUM(calories) > 150;