语法:select 分组函数,列(要求出现在group by的后面) from 表 【where 筛选条件】 group by 分组的列表 【order by 子句】
注意:查询列表必须特殊,要求是分组函数和group by后出现的字段
特点:1、分组查询中的筛选条件分为两类:
数据源 | 位置 | 关键字 | |
分组前筛选 | 原始表 | group by子句的前面 | where |
分组后筛选 | 分组后的结果集 | group by子句的后面 | having |
分组函数做条件,肯定放在having子句中
能用分组前筛选的,就优先考虑分组前筛选
2、group by子句支持单个字段分组,多个字段分组(多个字段之间用逗号隔开,没有排序要求),表达式过函数(用的较少)
3、也可以添加排序(排序放在整个分组查询的最后)
#案例一:查询每个工种的最低工资
select max(salary),job_id from employees group by job_id;
#案例二:查询每个位置上的部门个数
select count(department_id), location_id from departments group by location_id;
小技巧:“每个”的后面往往就是分组的列表
1、添加筛选的条件
#案例一:查询邮箱中包含a字符的,每个部门的平均工资
#包含字符a:where email like '%a%'
select avg(salary),department_id from employees where email like '%a%' group by department_id;
#案例二:查询有奖金的每个领导的手下员工的最高工资
select max(salary),manager_id from employees where commission_pct is not null group by manager_id;
2、添加复杂的筛选条件
#案例一:查询哪个部门的员工个数大于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;
#案例二:查询每个工种有奖金的员工的最高工资大于12000的工种编号和最高工资
select job_id,max(salary) from employees where commission_pct is not null group by job_id having max(salary) > 12000;
#案例三:查询领导编号大于102的每个领导手下最低工资大于5000的领导编号和最低工资
select min(salary),manager_id from employees where manager_id > 102 group by manager_id having min(salary) > 5000;
3、 按表达式或函数分组
#案例一:按员工姓名的长度分组,查询每个组的员工个数,筛选员工个数大于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;
4、按多个字段分组
#案例一:查询每个部门每个工种的员工的平均工资
select avg(salary), department_id, job_id from employees group by job_id, department_id;
5、按多个字段分组
#按多个字段分组
#案例一:查询每个部门每个工种的员工的平均工资,并且按照平均工资的高低排序
select avg(salary), department_id, job_id from employees where department_id is not null group by job_id, department_id order by avg(salary) desc;