以这张表为例(我们称之为BIN_TABLE
):
+------+------+
| A | B |
+------+------+
| 0 | 0 |
| 0 | 1 |
| 1 | 1 |
| 1 | 0 |
+------+------+
我想把它卷起来,所以我这样做:
SELECT A, B, COUNT(*)
FROM BIN_TABLE
GROUP BY A, B WITH ROLLUP;
我得到:
+------+------+----------+
| A | B | COUNT(*) |
+------+------+----------+
| 0 | 0 | 1 |
| 0 | 1 | 1 |
| 0 | NULL | 2 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
| 1 | NULL | 2 |
| NULL | NULL | 4 |
+------+------+----------+
这是一个如何WITH ROLLUP
使用我放在GROUP BY
子句中的字段顺序的示例。
我还想在结果中包含以下几行:
| NULL | 1 | 2 |
| NULL | 0 | 2 |
这意味着我拥有所有的汇总排列。
这是否可以不诉诸于此:
SELECT A, B, COUNT(*)
FROM BIN_TABLE
GROUP BY A, B WITH ROLLUP
UNION
SELECT NULL, B, COUNT(*)
FROM BIN_TABLE
GROUP BY B
(如果重要,我使用 MySQL 5.6)