第14节--分组查询
分组函数
特点:
1. 分组查询的筛选条件份两类数据源
① 分组前筛选,数据源为原始表,筛选放于Group by 子句前,关键词为Where;
② 分组后筛选,数据源为分组后的结果集,筛选放于Group by子句后面,关键词Having;
-----分组函数做条件,肯定是放在having 子句中
-----能用分组前筛选的就优先考虑使用分组前筛选
语法:
select 分组函数,列(要求出现在Group by的后面)
from employees
Group by 分组的列表
Order by 子句
注意:查询列表比较特殊,要求是分组函数和group by后的出现的字段
案例:
① 查询每个工种的最高工资
select max(salary) , job_id from employees group by job_id;
② 查询每个位置上的部门个数 select count(*), location_id from departments group by location_id;
③ 查询邮箱中包含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;(分组后筛选) select count(*), department_id from employees group by department_id having count(*)>2;
⑥ 查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资(分组后筛选) select max(salary), job_id 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;
⑧ 按员工姓名的长度分组,查询每一组员工的个数,筛选员工个数>5的有哪些? select count(*), length(last_name) len from employees group by len having len>5;
Jasminelee