Having表示对上述结果进行过滤,所以比Where更加灵活。Where之后不能跟聚合函数,因为where表示对每一行进行条件限制,此时聚合函数的值还没有求出,但是Having可以跟聚合函数,因为Having表示对结果进行过滤。
例子:求平均薪资大约2000的部门及部门薪资
参数:
employee表,包含所有信息
department 部门,string类型
salary 每个人的薪水,int类型
下面这个两个答案是错的:(where之后不能用聚合函数的信息)
答案1:
SELECT department,
avg(salary) AS sal
FROM employee
GROUP BY department
WHERE sal>2000 #Where在group by之前生效,所以就是说where后面不能写聚合函数
答案2:
SELECT department,
avg(salary) AS sal
FROM employee
GROUP BY department
WHERE avg(salary)>2000 #Where在group by之前生效,所以就是说where后面不能写聚合函数
正确答案:
- 用Having
SELECT department,
avg(salary) AS sal
FROM employee
GROUP BY department
HAVING sal>2000
- 用Where+subqueries
SELECT department,
sal
FROM (SELECT department,
avg(salary) AS sal
FROM employee
GROUP BY department)
WHERE sal>2000