- 我的电脑系统:Windows 10 64位
- SQL Server 软件版本: SQL Server 2014 Express
本篇博客里面使用了 scott
库,如何你现在还没有添加这个库到你的服务器里面,请在查看本篇博客前,访问这篇博文来在你的服务器里面附加scott
库。
group by
— 以某字段分组
1
2
3
4
| --输出每个部门的编号 和 该部门的平均工资
select deptno, avg(sal) as "部门平均工资"
from emp
group by deptno
|

1
2
3
4
| -- 判断下面语句是否正确
select deptno, avg(sal) as "部门平均工资" ename
from emp
group by deptno
|

总结: 使用了 group by
之后, select
中只能出现分组后的整体信息,不能出现组内的详细信息。
1
2
3
4
| --error
select *
from emp
group by deptno, job
|

1
2
3
4
| --error
select deptno, job, sal
from emp
group by deptno, job
|

1
2
3
| select deptno, job, avg(sal)
from emp
group by deptno, job
|

显示的不是很好,我们就对其进行排序。(没有实际的意义,我们就是讲讲语法。)
1
2
3
4
| select deptno, job, avg(sal)
from emp
group by deptno, job
order by deptno
|

只要是聚合函数,在这里都可以使用。
1
2
3
4
| select deptno, job, avg(sal), count(*), sum(sal), min(sal)
from emp
group by deptno, job
order by deptno
|

1
2
3
4
| select deptno, job, avg(sal) "平均工资", count(*) "部门人数", sum(sal) "部门总工资", min(sal) "部门最低工资"
from emp
group by deptno, job
order by deptno
|

总结:
group by
- 格式:
group by 字段的集合
- 功能:把表中的记录按照字段分成不同的组
- 注意:理解
group by a, b, c
的用法
- 先按
a
分组,如果 a
相同,再按 b
分组,如果 b
相同,再按 c
分组。最终统计的最小分组的信息。