当我使用group by … with rollup运行查询时:
select a, b, sum(c)
from <table>
group by a, b with rollup;
我在(我认为是)查询的PK(即group-by列)中获得了重复的行:
+------+------+--------+
| 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))
解决方法:
好问题.我能想到的一个选择就是这样做:
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;