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
的位置?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HAVING 可以在没有子查询的情况下实现这一点:
这会过滤掉除总计之外的汇总后行:
HAVING can do the trick with no subquery:
This filters out the post-rollup rows except for the grand total:
尝试使用子查询,例如 -
您可能还想用适当的文本更改 NULL 值。
Try to use a subquery, e.g. -
You also may want to change NULL values with appropriate texts.
在“名称”列下方,它将显示为“总计”。如果您遇到数字为空的问题,也可以这样做。
Below Name column it would Display as Total. If you have issue with number as null same can be done for that too.