資料經由 GROUP BY 分群後,如果要對分群後的資料來進行篩選,這時就可以使用 HAVING 來達成要求。同時,HAVING 一定要放在 GROUP BY 之後。
SELECT <Field 1><Field 2>......
FROM <TableName>
GROUP BY <Field 1><Field 2>......
HAVING <Rules>......;
SELECT → FROM → WHERE → GROUP BY → HAVING
這兩者都可達到篩選資料的功能,得看你的需求來進行調整。
SELECT category, COUNT(*) "Count"
FROM Product
GROUP BY category
HAVING COUNT = 5;
2. 若要搜尋符合:平均成本價大於 2000 的分類,就可以寫成如下:
SELECT category, AVG(cost_price) "AVG"
FROM Product
GROUP BY category
HAVING AVG(cost_price)>2000;