mysql分组查询(group by)

/*
进阶5:分组查询
语法:select 分组函数,列
		from 表
		【where + 条件】
		group by  分组列表
		【order by+子句】
注意:查询列表必循特殊,要求是分组函数和group by后出现的字段。
分组查询会意思是一个职业字段中的有十种不同的职业,但是从事这十种职业的有一百人,但是被group by之后只会出现十种的职业,即就是十种不同的职业。自动去重。 
*/
#案例:查询每个工种的最高工薪
select job_id,max(salary) from employees group by job_id;
#查询每个位置上的部门个数
select count(*),location_id from departments group by location_id;

#添加刷选条件
#案例:查询邮箱中的包含a的字符,每个部门的平均工资
select round(avg(salary),2),department_id,email 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;


/*
	分组查询的刷选条件分为两类:
						数据源    			位置			关键字
	分组前刷选 			原始表			group by子句前面	Where
	分组后刷选			分组后的结果集 		groupby子句后面	 having

	group 语句能支持单个字段,多个字段的分组
	也可以添加排序
*/
use myemployees;
#案例:查询那个部门的员工数大于2
select department_id,count(*) 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;

#案例;按员工姓名的长度分组,查询每一组的员工的个数,帅选出员工个数大与5
select  length(last_name) as '名字长度',count(*) from employees group by length(last_name) having count(*)>5 order by count(*) desc;

#查询领导编号>102的每个领导的手下的最低工资>5000的领导编号是哪个,以及最低工资
select manager_id ,min(salary) from employees where manager_id>102 group by manager_id having min(salary)>5000;

#按多个字段进行分组
#案例:查询每个部门每个工种的员工的平均工资
select  department_id,job_id,round(avg(salary),2) from employees group by department_id,job_id;

#添加排序
#案例:查询每个部门每个工种的员工的平均工资,并且按平均工资的高低进行排序
select  department_id,job_id,round(avg(salary),2) as '平均工资' from employees group by department_id,job_id order by 平均工资 desc;
#---------------------------------------------------------------------

#作业:查询各job_id 的员工工资的最大值,最小值,平均值,总和,并按job_id 升序

select job_id,max(salary) as '最大工资',min(salary) as '最小工资', avg(salary) as '平均工资' ,sum(salary) as '总和' 
from employees group by job_id order by job_id  asc;

#查询员工最高工资和最低工资的差距
select max(salary)-min(salary) as 'difference' from employees;

#查询各管理者的手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内
select manager_id,min(salary) as '最低工资' from employees where manager_id is not null group by manager_id having 最低工资 >=6000; 

#查询每个部门的编号,员工数量和工资平均值,并按平均工资降序
select  department_id,count(employee_id),avg(salary) from employees  where department_id is not null group by department_id order by avg(salary) desc;

#选择具有各个job_id 的员工人数
select job_id,count(*) from employees group by job_id;

 

你可能感兴趣的:(mysql分组查询(group by))