分组过滤:HAVING

create table employee
(

dept_name nvarchar(20),
salary int

);

insert into employee
values
(N'销售部',6000),
(N'销售部',8000),
(N'销售部',7000),
(N'技术部',12000),
(N'技术部',10000),
(N'行政部',4000);

select
dept_name as 部门,
count() as 部门人数
from employee
GROUP BY dept_name
having count(
) >=3;

select
dept_name as 部门,
avg(salary) as 平均工资
from employee
where salary > 5000
group by dept_name
having avg(salary) >=7000;

————————————————————————————————————

WHERE 过滤单行原始数据,写在 GROUP BY 前面
HAVING 过滤分组统计结果,写在 GROUP BY 后面
聚合函数(COUNT/AVG/SUM…)只能写在 HAVING 里,不能写在 WHERE 里
简单记:
筛数据用 WHERE
筛分组用 HAVING