You did not mention the DBMS. Assuming you are using MS SQL-Server, I found a T-SQL error message that is self-explanatory:
"An aggregate may not appear in WHERE if it is not in the subquery contained in the HAVING clause or selection list, and the aggregated column is an external link
http://www.sql-server-performance.com/
And an example of how this is possible in a subquery.
Show all customers and the smallest order for those who have 5 or more orders (and NULL for others):
SELECT a.lastname , a.firstname , ( SELECT MIN( o.amount ) FROM orders o WHERE a.customerid = o.customerid AND COUNT( a.customerid ) >= 5 ) AS smallestOrderAmount FROM account a GROUP BY a.customerid , a.lastname , a.firstname ;
UPDATE
The above actions are performed both in SQL-Server and in MySQL, but do not return the expected result. The next one is closer. I assume that this is due to the fact that the customerid , GROUPed BY field is used in the query-subquery connection in the first case PRIMARY KEY of the external table, and in the second case it is not.
Show all customer IDs and the number of orders for those who have 5 or more orders (and NULL for others):
SELECT o.customerid , ( SELECT COUNT( o.customerid ) FROM account a WHERE a.customerid = o.customerid AND COUNT( o.customerid ) >= 5 ) AS cnt FROM orders o GROUP BY o.customerid ;
Tim Schmelter Jun 11 2018-11-11T00: 00Z
source share