MySQL只获得整体ROLLUP

在按多个字段分组时执行WITH ROLLUP,MySQL返回每个组的汇总行以及总体摘要:

CREATE TABLE test (name VARCHAR(50), number TINYINT);
INSERT INTO test VALUES
    ('foo', 1), ('foo', 1), ('foo', 2), ('foo', 3), ('foo', 3),
    ('bar', 1), ('bar', 2), ('bar', 2), ('bar', 2), ('bar', 3),
    ('baz', 1), ('baz', 2), ('bar', 2);
SELECT name, number, COUNT(1) FROM test GROUP BY name, number WITH ROLLUP;

+------+--------+----------+
| name | number | count(1) |
+------+--------+----------+
| bar  |      1 |        1 |
| bar  |      2 |        3 |
| bar  |      3 |        1 |
| bar  |   NULL |        5 |
| baz  |      1 |        1 |
| baz  |      2 |        2 |
| baz  |   NULL |        3 |
| foo  |      1 |        2 |
| foo  |      2 |        1 |
| foo  |      3 |        2 |
| foo  |   NULL |        5 |
| NULL |   NULL |       13 |
+------+--------+----------+

我对foo / bar / baz的汇总不感兴趣,只对整体摘要感兴趣.实现这一目标的最有效方法是什么?

我知道由于之后添加了汇总行,我无法使用HAVING.对此使用嵌套查询的最佳解决方案是,选择名称和数字是NOT NULL还是NULL都是NULL?

解决方法:

HAVING可以完成没有子查询的技巧:

SELECT `name`, number, COUNT(1) FROM test GROUP BY `name`, number WITH ROLLUP 
HAVING number IS NOT NULL OR `name` IS NULL;

这会过滤掉汇总后的行,除了总计:

name    number  COUNT(1)
------  ------  --------
bar          1         1
bar          2         4
bar          3         1
baz          1         1
baz          2         1
foo          1         2
foo          2         1
foo          3         2
(NULL)  (NULL)        13
上一篇:GROUP BY你都不会!ROLLUP,CUBE,GROUPPING详解


下一篇:Codeforces Gym 100650C The Game of Efil DFS