MySQL_Sql_打怪升级_进阶篇_进阶5:分组查询

进阶5:分组查询

语法:

select 查询列表
from 表
【where 筛选条件】
group by 分组的字段	
having
【order by 排序的字段】;

特点:

1、和分组函数一同查询的字段必须是group by后出现的字段
2、筛选分为两类:分组前筛选和分组后筛选

​		   针对的数据源		 位置		     连接的关键字

分组前筛选	原始表			  group by前	     where
分组后筛选	分组后的结果集    	  group by后         having

	①分组函数做条件的,肯定是要放到having子句中
	②能用分组前筛选的,尽量使用分组前筛选,提高效率

3、分组可以按单个字段也可以按多个字段分组,(多个字段之间用逗号隔开没有顺序要求)支持的表达式用的较少
4、可以添加排序使用(排序放到整个分组的最后)

引入:查询每个部门的员工个数

SELECT COUNT(*) FROM employees WHERE department_id=90;

5.1简单的分组

案例1:查询每个工种的员工平均工资

SELECT AVG(salary),job_id
FROM employees
GROUP BY job_id;

案例2:查询每个位置的部门个数

SELECT COUNT(*),location_id
FROM departments
GROUP BY location_id;

5.2可以实现分组前的筛选

案例1:查询邮箱中包含a字符的 每个部门的最高工资

SELECT MAX(salary),department_id
FROM employees
WHERE email LIKE '%a%'
GROUP BY department_id;

案例2:查询有奖金的每个领导手下员工的平均工资

SELECT AVG(salary),manager_id
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY manager_id;

5.3可以实现分组后筛选

案例1:查询哪个部门的员工个数>5

①查询每个部门的员工个数
SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id;

② 筛选刚才①结果

SELECT COUNT(*),department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*)>5;

案例2:每个工种有奖金的员工的最高工资>12000的工种编号和最高工资

SELECT job_id,MAX(salary)
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING MAX(salary)>12000;

案例3:领导编号>102的每个领导手下的最低工资大于5000的领导编号和最低工资

SELECT manager_id,MIN(salary)
FROM employees
WHERE manager_id>102
GROUP BY manager_id
HAVING MIN(salary)>5000;

5.4按照表达式或者函数分组

案例:按员工姓名的长度分组,查询每一组的员工数,筛选员工个数>5的有哪些

SELECT COUNT(*),LENGTH(last_name) len_name
FROM employees
GROUP BY LENGTH(last_name)
HAVING COUNT(*)>5;

#------------------------------
SELECT COUNT(*) c ,LENGTH(last_name) len_name
FROM employees
GROUP BY len_name
HAVING c>5;

注意:在MySQL中 having 支持别名,oracle是不支持的。

5.5按多个字段分组

案例:查询每个工种每个部门的最低工资,并按最低工资降序

SELECT MIN(salary),job_id,department_id
FROM employees
GROUP BY department_id,job_id
ORDER BY MIN(salary) DESC;

5.6添加排序

案例:查询每个工种有奖金的员工的最高工资>6000的工种编号和最高工资,按最高工资升序

SELECT job_id,MAX(salary) m
FROM employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING m>6000
ORDER BY m ;

5.7分组查询习题

#1.查询各job_id的员工工资的最大值,最小值,平均值,总和,并按job_id升序
SELECT MAX(salary),MIN(salary),AVG(salary),SUM(salary),job_id
FROM employees
GROUP BY job_id
ORDER BY job_id;

#2.查询员工最高工资和最低工资的差距(DIFFERENCE)
SELECT MAX(salary) - MIN(salary) AS DIFFERENCE
FROM employees;

#3.查询员工表中的最大入职时间和最小入职时间的相差天数(DIFFERENCE)
SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) AS DIFFERENCE
FROM employees;

#4.查询各个管理者手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内
SELECT MIN(salary),manager_id
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary)>=6000;

#5.查询所有部门的编号,员工数量和工资平均值,并按平均工资降序
SELECT department_id,COUNT(*),AVG(salary) a
FROM employees
GROUP BY department_id
ORDER BY a DESC;

#6.查询各个job_id的员工人数
SELECT COUNT(*) 个数,job_id
FROM employees
GROUP BY job_id;
posted @ 2020-09-03 13:07  oldliych  阅读(199)  评论(0编辑  收藏  举报