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 in SQL Server
For demonstration we have a table named ‘Info’ with some records.
--Select records from info
SELECT * FROM INFO
Problem Statement: Find all the details of INFO for the max id.
SELECT * FROM INFO WHERE ID = MAX(ID)
When he executed above script it gave him following error:
Msg 147, Level 15, State 1, Line 3
An aggregate may not appear in the WHERE clause unless it is in a sub query contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
He was not able to resolve this problem, even though the solution was given in the query description itself. Due to lack of experience he came up with another version of above query based on the error message.
SELECT * FROM INFO HAVING ID = MAX(ID)
Msg 8121, Level 16, State 1, Line 1
Column 'INFO.id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
What he wanted actually was the table INFO max value of ID. Based on the problem statement what the right solution is as following, which does not generate error.
SELECT * FROM INFO WHERE ID = (SELECT MAX(ID) FROM INFO)