这周看代码,看到了一个sql语法,使用的是group by rollup,一开始看文档没有明白,后来写了个例子又问了问别人才明白。不多说直接上例子,因为是例子所以就不要纠结字段类型了。
首先创建一张表
CREATE TABLE "user" (
"id" int(11) NOT NULL AUTO_INCREMENT,
"name" varchar(20) DEFAULT NULL,
"sex" varchar(1) DEFAULT NULL,
"did" varchar(1) DEFAULT NULL,
PRIMARY KEY ("id")
)
然后自己添加了部分数据,使用select命令进行查看
select * from user;
| id | name | sex | did |
+----+----------+------+------+
| 1 | 小明 | 0 | 1 |
| 2 | 小明01 | 0 | 1 |
| 3 | 小明02 | 0 | 1 |
| 4 | 小明04 | 0 | 1 |
| 5 | 小明04 | 0 | 1 |
| 6 | 小黑01 | 1 | 1 |
| 7 | 小黑01 | 1 | 1 |
| 8 | 小红01 | 0 | 2 |
| 9 | 小胡01 | 1 | 2 |
| 10 | 小胡02 | 1 | 2 |
| 11 | 小胡04 | 0 | 3 |
| 12 | 小胡03 | 0 | 2 |
| 13 | 小蓝01 | 1 | 3 |
| 14 | 小蓝02 | 1 | 3 |
| 15 | 小其01 | 1 | 3 |
| 16 | 小其02 | 0 | 3 |
首先先根据sex和did分别进行分组查询
根据sex分组
select sex as 性别 , count(*) as 总数 from user group by(sex);
+--------+--------+
| 性别 | 总数 |
+--------+--------+
| 0 | 9 |
| 1 | 7 |
+--------+--------+
根据did分组
select did as 部门 , count(*) as 总数 from user group by(did);
+--------+--------+
| 部门 | 总数 |
+--------+--------+
| 1 | 7 |
| 2 | 4 |
| 3 | 5 |
+--------+--------+
然后使用group by rollup对sex进行分组
select sex as 性别 , count(*) as 总数 from user group by rollup(sex);
+--------+--------+
| 性别 | 总数 |
+--------+--------+
| 0 | 9 |
| 1 | 7 |
| NULL | 16 |
+--------+--------+
使用group by rollup对did进行分组
select did as 部门 , count(*) as 总数 from user group by rollup(did);
+--------+--------+
| 部门 | 总数 |
+--------+--------+
| 1 | 7 |
| 2 | 4 |
| 3 | 5 |
| NULL | 16 |
+--------+--------+
到这里可以看出来,group by rollup其实就是在group by的基础上做了一个合计
接下来,用group by sex和did进行分组
select sex as 性别 , did as 部门 , count(*) as 总数 from user group by rollup(sex,did);
+--------+--------+--------+
| 性别 | 部门 | 总数 |
+--------+--------+--------+
| 0 | 1 | 5 |
| 1 | 1 | 2 |
| 0 | 2 | 2 |
| 1 | 2 | 2 |
| 0 | 3 | 2 |
| 1 | 3 | 3 |
| 0 | NULL | 9 |
| 1 | NULL | 7 |
| NULL | NULL | 16 |
+--------+--------+--------+
9 rows in set (Elapsed: 00:00:00.01)
结果可能不太好理解,其实就是首先对sex和did进行分组,然后再对sex进行分组,最后再加上合计,
相当于(2*3 + 2 + 合计(NULL),因此有9条出现)
接下来出现一个问题,变换顺序用group by rollup对did和sex进行分组时
select sex as 性别 , did as 部门 , count(*) as 总数 from user group by rollup(did,sex);
+--------+--------+--------+
| 性别 | 部门 | 总数 |
+--------+--------+--------+
| 0 | 1 | 5 |
| 1 | 1 | 2 |
| 0 | 2 | 2 |
| 1 | 2 | 2 |
| 0 | 3 | 2 |
| 1 | 3 | 3 |
| NULL | 1 | 7 |
| NULL | 2 | 4 |
| NULL | 3 | 5 |
| NULL | NULL | 16 |
+--------+--------+--------+
10 rows in set (Elapsed: 00:00:00.00)
发现结果多了一条
原因是变换顺序后首先对sex和did进行分组,然后再对did进行分组,最后再加上合计,
就变成了(3*2 + 3 + 合计(NULL)),因此可以看到最后的条数多了一条