MySQL仅获得整体ROLLUP [英] MySQL only get overall ROLLUP
问题描述
当按多个字段分组时执行WITH ROLLUP
,MySQL为每个组返回汇总行,以及整体摘要:
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 |
+------+--------+----------+
我对foo/bar/baz的汇总不感兴趣,仅对整体摘要感兴趣.实现此目标的最有效的方法是什么?
I'm not interested in the rollups for foo/bar/baz, only the overall summary. What's the most efficient way to achieve this?
我知道我不能使用HAVING
,因为之后会添加汇总行.最好的解决方案是为此使用嵌套查询,选择名称和数字都是NOT NULL
还是NULL
的地方?
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
?
推荐答案
HAVING可以在没有子查询的情况下完成任务:
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
这篇关于MySQL仅获得整体ROLLUP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!