SQL语句之分组查询–GROUP BY(group by)
语法
select 聚合函数,列(要求出现在group by的后面)from 表where 筛选条件group by 分组的列表order by 子句
注意:除了出现在group by后面的字段,如果要在select后查询其他字段,必须用聚合函数进行聚合
特点:分组查询中的筛选条件分为两类: 分组前筛选: 数据源是原始表,用where,放在group by前面,因为在分组前筛选 分组后筛选:数据源是分组后的结果集 ,用having,放在group by后面,因为在分组后进行筛选
例1:
select max(salary),job_idfrom employeesgroup by job_id;
目的:查询最高工资的员工
例2:
select avg(salary),department_idfrom employeeswhere email like '%a%'group by department_id
目的:查询邮箱中包含a字符的每个部门的平均工资
例3:
select max(salary),manager_id from employeeswhere commission_pct is not nullgroup by manager_id
目的:查询有奖金的每个领导手下最高工资的员工工资
例4:
select count(*),department_id from employees group by department_id having count(*) > 2;
目的:查询哪个部门的员工个数大于2
思路:
查询每个部门的员工个数;根据1的结果进行筛选,查询哪个部门员工个数大于2
注:分组前的筛选用where,分组后的筛选用having
例5:
select max(salary),job_idfrom employeeswhere commission_pct is not nullgroup by job_id having max(salary) > 12000;
目的:查询每个工种有奖金的员工的最高工资大于12000的工种编号和最高工资
思路:
查询每个工资有奖金的员工的最高工资;根据最高工资筛选大于12000的工种编号;
按表达式或函数进行筛选
例5:
select count(*) ,length(last_name) as len_namefrom employees group by length(last_name)having count(*) > 5;
目的:按照员工姓名长度分组,查询每一组员工个数,筛选员工个数大于5的有哪些
按照多个字段分组
例6:
select avg(salary),department_id,job_id from employeeswhere department_id is not nullgroup by department_id,job_idorder by avg(salary) desc;
目的:查询每个部门每个工种的员工平均工资,并且按照平均工资的高低排序