In a test at university there was a question; is it possible to use an aggregate function in the SQL WHERE clause.
I always thought this isn’t possible and I also can’t find any example how it would be possible. But my answer was marked false and now I want to know in which cases it is possible to use an aggregate function in the WHERE. Also if it isn’t possible it would be nice to get a link to the specification where it is described.
You haven’t mentioned the DBMS. Assuming you are using MS SQL-Server, I’ve found a T-SQL Error message that is self-explanatory:
http://www.sql-server-performance.com/
And an example that it is possible in a subquery.
Show all customers and smallest order for those who have 5 or more orders (and NULL for others):
UPDATE.
The above runs in both SQL-Server and MySQL but it doesn’t return the result I expected. The next one is more close. I guess it has to do with that the field
customerid, GROUPed BY and used in the query-subquery join is in the first case PRIMARY KEY of the outer table and in the second case it’s not.Show all customer ids and number of orders for those who have 5 or more orders (and NULL for others):