-- SQL Server中的聚合函数有:聚合数据(group by)后面不能跟过滤条件where
1.count() 所有记录du数
2.count(*)所有非null记录数
3.avg() 某一列平均值
4.min() 某一列最小值
5.max() 某一列最大值
6.sum() 某一列总和
-- 聚合数据(group by)后面不能跟过滤条件where,会报错
SELECT title ,COUNT(*) FROM employee GROUP BY title WHERE title = 'ce_shi';
-- 聚合数据(group by)前面可以跟过滤条件where(此时where过滤的是原始数据)
SELECT title, COUNT(*) FROM employee WHERE title = 'ce_shi' GROUP BY title;
-- HAVING 子句:
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。
语法:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
-- having可以跟在聚合数据(group by)后面
SELECT title,COUNT(*) FROM employee GROUP BY title HAVING title = 'ce_shi';
-- having不可以跟在聚合数据(group by)前面
SELECT title, COUNT(*) FROM employee HAVING title = 'ce_shi' GROUP BY title;