MySQL only get overall ROLLUP

cmbuckley picture cmbuckley · Jan 12, 2012 · Viewed 9.3k times · Source

Performing a WITH ROLLUP when grouping by multiple fields, MySQL returns a rollup row for each group, as well as the overall summary:

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 |
+------+--------+----------+

I'm not interested in the rollups for foo/bar/baz, only the overall summary. What's the most efficient way to achieve this?

I know I can't use HAVING due to the rollup rows being added afterwards. Is the best solution to use a nested query for this, selecting where name and number are either both NOT NULL or both NULL?

Answer

LukeVI picture LukeVI · Nov 2, 2016

HAVING can do the trick with no subquery:

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

This filters out the post-rollup rows except for the grand total:

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