获取行组的聚合结果
根据特定列值计算行数:
SELECT category, COUNT(*) AS item_count
FROM item
GROUP BY category;
按部门获得平均收入:
SELECT department, AVG(income)
FROM employees
GROUP BY department;
重要的是只选择 GROUP BY
子句中指定的列或与聚合函数一起使用 。
有 WHERE
子句也可以和 GROUP BY
一起使用,但 WHERE
在任何分组完成之前过滤掉记录 :
SELECT department, AVG(income)
FROM employees
WHERE department <> 'ACCOUNTING'
GROUP BY department;
如果你需要在分组完成后过滤结果,例如,仅查看平均收入大于 1000 的部门,则需要使用 HAVING
子句:
SELECT department, AVG(income)
FROM employees
WHERE department <> 'ACCOUNTING'
GROUP BY department
HAVING avg(income) > 1000;