Mysql-DQL(分组查询)

进阶5:分组查询

语法:
select 查询列表
from 表
【where 筛选条件】
group by 分组的字段
【order by 排序的字段】;
注意:
查询列表必须特殊,要求是分组函数和group by后出现的字段

特点:
1、分组查询中的筛选条件分两类

数据源 位置 关键字
分组前筛选 原始表 group by前面 where
分组后筛选 分组后的结果集 group by后面 having

分组函数做条件肯定放在having中
group by 子句支持单个字段分组,多个字段分组、函数、表达式、可以接排序放在最后

分组函数:
count
sum
max
min
avg

#查询每个部门的员工个数
SELECT COUNT(*) FROM employees WHERE department_id=90;
#案例1:查询每个工种的员工平均工资
SELECT AVG(salary),job_id
FROM employees
GROUP BY job_id;

添加分组后的筛选条件

#案例1 查询那个部门的员工数>2
#1.查询每个部门的员工个数
#2.根据1的结果进行筛选,查询那个部门的员工个数>2
/*
不能用where因为where是从你原始表里面筛选 并且更在from后面 而现在要求是在结果的新建表里面进行筛选 用having
*/
select count(*),department_id from employees 
group by department_id 
having count(*)>2;
#案例2: 查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资
 select
  max(salary),
  job_id
from
  employees
where commission_pct is not  null
group by job_id
having max(salary)>12000;
#按多个字段分组
#案例:查询每个部门每个工种的平均工资
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;
发布了45 篇原创文章 · 获赞 43 · 访问量 7085

猜你喜欢

转载自blog.csdn.net/qq_42193790/article/details/104354099