The HAVING clause is optional and qualifies a GROUP BY clause. It is similar to the WHERE clause, but the HAVING clause establishes restrictions that determine which records are displayed after they have been grouped.
SELECT Product, COUNT(Product) AS Tally FROM Suppliers
GROUP BY Product HAVING COUNT(Product) > 1;
Product Tally
Desktop 25
Laptop 19
Mouse 33
Network Card 3
Software 4
Book 6
Accessory 7
(7 row(s) affected)
This example displays a list of different products, along with their count, but only where there are more than one.
SELECT Item, COUNT(Item) AS Tally, MAX(UnitPrice) AS MaxPrice
FROM Products GROUP BY Item
HAVING COUNT(Item) > 1 AND MAX(UnitPrice) < 400;
Item Tally MaxPrice
Intellisense Mouse 20 20.00
Travelstar 30gb Hard Drive 3 100.00
(2 row(s) affected)
This example returns a list of items only where the whole group meets the criteria of the HAVING clause, that is only items of which there are more than 1, and none of which cost more than $400. This is an example of linking multiple expressions together by logical operators such as AND and OR. A HAVING clause can contain up to forty (40) such expressions.
SELECT Item, COUNT(Item) AS Tally, MAX(UnitPrice) AS MaxPrice
FROM Products WHERE UnitPrice < 400
GROUP BY Item HAVING COUNT(Item) > 1;
Item Tally MaxPrice
Dell Axim X30 13 379.00
Intellisense Mouse 20 20.00
Travelstar 30gb Hard Drive 3 100.00
(3 row(s) affected)
This query shows how to count only those items that cost less that $400 (there could be others that cost more) and that number more than 1.