首页 小组 文章 相册 留言本 用户 搜索 我的社区 在线学堂 商城 购物车 支付钱包

[打卡]更正 HAVING

2024-05-08 15:16:56
0
172

GROUP BY

#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
GROUP BY department_id;
HAVING max(salary)>10000
#要求2;HAVING必须声明在GROUP BY 后面

#以上为规范


#思考:没有GROUP BY 能不能用HAVING
SELECT department_id,max(salary)
FROM employees
HAVING max(salary)>10000
#要求三:虽然没有GROUP BY能运行GROUP BY ,但是实际开发中,我们使用having的前提是sql中使用了GROUP BY
#练习

#方式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 department_id in(10,20,30,40) AND max(salary)>10000;

#结论1:当过滤条件中有聚合函数时,则此过滤条件必须声明在HAVING中

#结论2:当过滤条件中没有聚合函数时,则此过滤条件声明在where和HAVING中都可已 建议声明在WHERE里

/*
1 从适用范围来讲HAVING的适用范围更广

2 如果过滤条件中没有聚合函数,这种情况下,WHERE的执行效率高于HAVING

*/

SELECT max(salary),MIN(salary),AVG(salary),SUM(salary)
FROM employees

#练习题
SELECT job_id,MAX(salary),MIN(salary),AVG(salary)
FROM employees
GROUP BY job_id;

SELECT job_id ,COUNT(job_id)
FROM employees
GROUP BY job_id;

SELECT(MAX(salary)-MIN(salary))as salary
from employees

SELECT manager_id ,MIN(salary)
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary)>6000;

SELECT department_name,location_id,COUNT(employee_id),AVG(salary)avg_sal
FROM employees e
RIGHT JOIN departments d
ON e.department_id=d.department_id
ORDER BY avg_sal DESC

评论
意见反馈