有如下数据:
一个简单的分组查询案例
[En]
A simple case of grouping query
按照部门编号deptno分组,统计每个部门的平均工资。
select deptno,avg(sal) avgs
from emp
group by deptno;
结果如下:
group by关键字语法详解
group by
是用于 分组查询的关键字,一般是配合 sum(),avg(),count(),max(),min()
聚合函数使用的。也就是说SQL语句中只要有 group by
,那么在select后面的展示字段中一般会有聚合函数(5个聚合函数
)中的一个或多个函数出现。观察上图用表中的字段A进行分组后,一般就需要对表中的其它字段,使用聚合函数,这样意义更大,而不是还对字段A使用聚合函数。
当SQL语句中使用了 group by
后,在select后面一定有一个字段使用了聚合函数(5个聚合函数
)。但是除了这个聚合函数,select后面还可以添加其他什么字段吗?
答案肯定是可以的!但是该字段有一定的限制,并不是什么字段都可以。也就是说,当SQL语句中使用了 group by
关键字后,select后面除了聚合函数,就只能是 group by
后面出现的字段。也就是图中的 字段A
,select后面只能存在 group by
后面的字段。
分组前筛选和分组后筛选
原始表和结果集的概念
- 原始表指的是数据库中 真正存在的那个表,使用【select * from 表名】查询出来的就是原始表信息。
- 结果集指的是在SQL语句中,添加其它任何一个限制条件,最终展示给我们表,都是结果集。添加不同的限制条件,查询出来的结果集也是不同的。
- 原始表只有一个, 结果集却是各种各样的。
where筛选和having筛选选用
- 只要将聚合函数作为需求中的条件,就必须是分组后的筛选
[En]
as long as the aggregate function is used as a condition in the requirement, it must be the screening after grouping*
- 如果可以使用预分组筛查,将优先考虑预分组筛查。(考虑性能问题)
[En]
if pre-grouping screening can be used, priority will be given to pre-grouping screening. (considering performance issues)*
分组前筛选
- 查询姓名中包含S字符的,每个部门的工资之和。
select deptno,sum(sal)
from emp
where ename like '%S%'
group by deptno;
- 查询工资大于2000的,不同部门的平均工资。
select deptno,avg(sal)
from emp
where sal > 2000
group by deptno;
分组后筛选
- 查询部门员工个数大于3的部门编号和员工个数。
select deptno,count(*)
from emp
group by deptno
haveing count(*) > 3;
- 查询每个最高工资大于3000的部门的部门号和最高工资。
[En]
query the department number and maximum wage of each department whose maximum wage is greater than 3000.*
select deptno,max(sal) maxsfrom empgroup by deptnohaving maxs count(*) > 3;
分组前筛选和分组后筛选合用
- 查询1981年入职的,不同部门间工资的平均值大于2000的部门编号和平均值。
select deptno,avg(sal) avgs
from emp
where year(hiredate) = '1981'
group by deptno
having avgs > 2000;
分组查询(按函数分组)
- 按员工姓名长度分组,查询每个组的员工人数,筛选员工人数超过3人的?
[En]
grouped according to the length of employees’ names, query the number of employees in each group, and screen those whose number of employees is more than 3?*
select length(ename) len, count(*) countsfrom empgroup by lenhaving counts > 3;
分组查询(按多个字段分组)
- 查询各部门各工种员工的平均薪酬。
[En]
inquire about the average salary of employees of each type of work in each department.*
select deptno,jop,avg(sal) avgsfrom empgroup by deptno,job;
group by和order by
- 按平均工资降序查询各部门员工平均工资
[En]
query the average wages of employees in each department, according to the descending order of average wages.*
select deptno,jop,avg(sal) avgsfrom empgroup by deptnoorder by avgs desc;
- 按平均工资涨幅顺序,查询各部门员工平均工资
[En]
inquire about the average wages of employees in each department, according to the order of increase in average wages.*
select deptno,jop,avg(sal) avgsfrom empgroup by deptnoorder by avgs asc;
总结
- 分组函数做条件,肯定是放在
having
子句中。 - 能用分组前筛选的,就优先考虑使用分组前筛选。(
where
筛选) group by
子句支持单个字段分组,多个字段分组(多个字段之间用逗号隔开没有顺序要求),还支持函数分组(用的较少)。
Original: https://www.cnblogs.com/pure3417/p/15224587.html
Author: pure3417
Title: MySQL之group by分组查询
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/508187/
转载文章受原作者版权保护。转载请注明原作者出处!