当我使用group by ... with rollup以下命令运行查询时:
group by ... with rollup
select a, b, sum(c) from <table> group by a, b with rollup;
我在查询的PK(即分组依据列)中得到了重复的行(我认为是):
+------+------+--------+ | a | b | sum(c) | +------+------+--------+ | NULL | NULL | 13 | | NULL | 1 | 4 | | NULL | 3 | 8 | | NULL | 4 | 9 | | NULL | NULL | 34 | | 1 | 3 | 17 | | 1 | 4 | NULL | | 1 | 17 | 2 | | 1 | NULL | 19 | | 2 | NULL | 6 | | 2 | 1 | 17 | | 2 | 3 | 17 | | 2 | NULL | 40 | | 4 | 17 | 2 | | 4 | NULL | 2 | | 5 | NULL | 11 | | 5 | 6 | 7 | | 5 | NULL | 18 | | 13 | 4 | 2 | | 13 | NULL | 2 | | 14 | 41 | 3 | | 14 | NULL | 3 | | 18 | 1 | 2 | | 18 | NULL | 2 | | 41 | 2 | 17 | | 41 | NULL | 17 |
…更多行跟随…
如何区分(NULL, NULL, 13)从(NULL, NULL, 34)? 也就是说,如何区分由于基础数据而为空的行和因汇总而添加为空的行?(请注意,还有更多示例-(2, NULL, 6)和(2, NULL, 40))
(NULL, NULL, 13)
(NULL, NULL, 34)
(2, NULL, 6)
(2, NULL, 40)
好问题。我可以想到的一种选择是:
select COALESCE(a, -1) AS a, COALESCE(b, -1) AS b, sum(c) from <table> group by COALESCE(a, -1), COALESCE(b, -1) with rollup;