# HAVING的使用(作用:用来过滤数据的)
#(WHERE 也是过滤数据的)
# GROUP BY分组之后,提到HAVING
#从需求出发
#练习:查询各个部门中最高工资比10000高的部门信息
#错误示范
SELECT department_id,MAX(salary)
FROM employees
WHERE MAX(salary)>10000
GROUP BY department_id;
#正确写法
#要求1:如果过滤条件中使用了聚合函数,则必须使用HAVING
SELECT department_id,MAX(salary)
FROM employees
HAVING MAX(salary)>10000
GROUP BY department_id;
#要求2:HAVING必须声明在GROUP BY的后面(规范)
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000;
#思考:没有GROUP BY还能不能用HAVING?
SELECT department_id,MAX(salary)
FROM employees
HAVING MAX(salary)>10000;
#要求3:虽然没有GROUP BY能运行 HAVING,但是实际开发中,我们
#使用 HAVING的前提是SQL中使用了GROUP BY
#练习:查询部门id为10,20,30,40这4个部门中最高工资比10000高的部门信息
#方式1:
SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN (10,20,30,40)
GROUP BY department_id
HAVING MAX(salary)>10000;
#方式2:
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 AND department_id IN (10,20,30,40);
#结论1:当过滤条件中有聚合函数时,则过滤条件必须声明在HAVING中
#结论2:当过滤条件中没有聚合函数时,则此过滤条件声明在WHERE和 HAVING中都可以
/*
1.从适用范围上来讲,HAVING的适用范围更广
2.如果过滤条件中没有聚合函数,WHERE的执行效率要高于HAVING
*/