Use HAVING with Aggregate Functions
suggest changeUnlike the WHERE clause, HAVING can be used with aggregate functions.
An aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement (Wikipedia).
Common aggregate functions include COUNT(), SUM(), MIN(), and MAX().
This example uses the Car Table from the Example Databases.
SELECT CustomerId, COUNT(Id) AS "Number of Cars"
FROM Cars
GROUP BY CustomerId
HAVING COUNT(Id) > 1
This query returns the CustomerId and car count of any customer who has more than one car. In the sample, that is only customer 1 (two Ford F-150s). Quoted aliases are delimited identifiers; brackets are the SQL Server spelling. HAVING cannot use the select-list alias in standard SQL.
The results will look like:
CustomerId | Number of Cars |
––––– | ––––––– |
1 | 2 |