引入: 查询每个部门的平均工资?
语法:
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(*),location_id from departments group by location_id;
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;
step1. 查询每个部门的员工个数
step2. 根据step1的结果进行筛选,查询哪个部门员工个数大于2
select count(*),department_id
from employees
group by department_id
having count(*)>2; # 分组后筛选,使用having
select max(salary),job_id
from employees
where commission_pct is not null
group by job_id
having max(salary)>12000;
select min(salary),manager_id
from employees
where manager_id>102
group by manager_id
having min(salary)>5000;
select count(*),length(last_name) as len_name
from employees
group by length(last_name) # 按表达式或函数分组
having count(*)>5; # having后支持用别名,where不支持,order by也支持
select avg(salary),department_id,job_id
from employees
group by department_id,job_id; # 多个字段分组。可调换位置
select avg(salary),department_id,job_id
from employees
where department_id is not null
group by department_id,job_id
having avg(salary)>10000
order by avg(salary) desc; # 排序放在最后