引入
查询每个部门的平均工资
如果用:
SELECT AVG(salary) FROM employees;
则查询的是所有部门的平均工资。下图表示了所有部门的平均工资和每个部门的平均工资:
分组查询语法
select 分组函数,列(要求出现在group by的后面)
from 表
【where 筛选条件】
group by 分组的列表
【order by 子句】
注意:查询列表必须特殊,要求是分组函数和group by后出现的字段
特点:
2.group by子句支持单个字段分组,多个字段分组(多个字段之间用逗号隔开没有顺序要求),表达式或函数(用的较少)
3.也可以添加排序(排序放在整个分组查询的最后)
6.1 简单的分组查询
案例1:查询每个工种的最高工资
SELECT
MAX(salary),
job_id
FROM
employees
GROUP BY job_id ;
结果:
案例2:查询每个位置上的部门个数
SELECT
COUNT(*),
location_id
FROM
departments
GROUP BY location_id ;
结果:
6.2 添加筛选条件
案例1:查询邮箱中包含a字符的,每个部门的平均工资
SELECT
AVG(salary),
department_id
FROM
employees
WHERE email LIKE "%a%"
GROUP BY department_id ;
案例2:查询有奖金的每个领导手下员工的最高工资
SELECT
MAX(salary),
manager_id
FROM
employees
WHERE commission_pct IS NOT NULL
GROUP BY manager_id ;
结果:
6.3 添加复杂的筛选条件
案例1:查询哪个部门的员工个数大于2
第一步:查询每个部门的员工数
SELECT
COUNT(*),
department_id
FROM
employees
GROUP BY department_id ;
结果:
第二步:根据第一步的结果进行筛选,查询哪个部门的员工个数大于2
SELECT
COUNT(*),
department_id
FROM
employees
GROUP BY department_id
HAVING COUNT(*) > 2 ;
结果:
案例2:查询每个工种有奖金的员工的最高工资大于12000的工种编号和最高工资
第一步:查询每个工种有奖金的员工的最高工资
SELECT
MAX(salary),
job_id
FROM
employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
第二步:根据第一步结果继续筛选,最高工资大于12000
SELECT
MAX(salary),
job_id
FROM
employees
WHERE commission_pct IS NOT NULL
GROUP BY job_id
HAVING MAX(salary) > 12000;
案例3:查询领导编号大于102的每个领导手下的最低工资大于5000的领导编号是哪个,以及其最低工资
SELECT
MIN(salary),
manager_id
FROM
employees
WHERE manager_id > 102
GROUP BY manager_id
HAVING MIN(salary) > 5000 ;
6.4 按表达式或函数分组
案例:按员工姓名的长度分组,查询每一组的员工个数,筛选员工个数大于5的有哪些
SELECT
COUNT(*),
LENGTH(last_name) AS "len_name"
FROM
employees
GROUP BY LENGTH(last_name)
HAVING COUNT(*) > 5 ;
6.5 按多个字段分组
案例:查询每个部门每个工种的员工的平均工资
SELECT
AVG(salary),
department_id,
job_id
FROM
employees
GROUP BY department_id,
job_id ;
6.6添加排序
案例:查询每个部门每个工种的员工的平均工资,并且按平均工资的高低显示
SELECT
AVG(salary),
department_id,
job_id
FROM
employees
GROUP BY department_id,
job_id
ORDER BY AVG(salary) DESC;
小测试
1.查询个job_id的员工工资的最大值、最小值、平均值、总和,并按按job_id升序
SELECT
MAX(salary),
MIN(salary),
AVG(salary),
SUM(salary)
FROM
employees
GROUP BY job_id
ORDER BY job_id ;
2.查询员工最高工资和最低工资的差距(DIFFERENCE)
SELECT
MAX(salary) - MIN(salary) AS "DIFFERENCE"
FROM
employees ;
3.查询各个管理者手下员工的最低工资,其中最低工资不低于6000,没有管理者的员工不计算在内
SELECT
MIN(salary),
manager_id
FROM
employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary) >= 6000 ;
4.查询所有部门的编号,员工数量和工资平均值,并按平均工资降序
SELECT
department_id,
COUNT(*),
AVG(salary) AS "a"
FROM
employees
GROUP BY department_id
ORDER BY a DESC ;
5.选择具有各个job_id的员工人数
SELECT
COUNT(*) AS "个数",
job_id
FROM
employees
GROUP BY job_id ;