【SQL】group by rollup的使用
阿新 • • 發佈:2018-11-08
這周看程式碼,看到了一個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)),因此可以看到最後的條數多了一條