SQL查询" group by with cube"和NULL值

时间:2014-10-01 14:07:02

标签: sql sql-server group-by

我有一张表:

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| A    | 1    | foo  |
| A    | 1    | foo  |
| A    | 2    | foo  |
| B    | 1    | foo  |
| B    | 2    | foo  |
| B    | NULL | foo  |
| NULL | 1    | foo  |
+------+------+------+

我希望看到按foocol1分组的col2的数量:

+-------+---+---+------+-------+
|       | A | B | NULL | TOTAL |
+-------+---+---+------+-------+
| 1     | 2 | 1 |    1 |     4 |
| 2     | 1 | 1 |    0 |     2 |
| NULL  | 0 | 1 |    0 |     1 |
| TOTAL | 3 | 3 |    1 |     7 |
+-------+---+---+------+-------+

我使用这样的查询:

select 
    col1,
    col2,
    count(col3)
from table
group by 
    col1,
    col2 
with cube

我有4行col1col2NULL代表NULL/NULLNULL/TOTALTOTAL/NULL,{{1但是sql的总数有TOTAL/TOTAL值。

是否可以为查询中的总计设置与NULL不同的自定义值?

1 个答案:

答案 0 :(得分:3)

我会使用一些条件聚合以及子查询,因为你想使用" null"作为实际价值。

select 
  col2 = Isnull(col2, 'Total'), 
  A = sum(case when col1 = 'A' then 1 else 0 end),
  B = sum(case when col1 = 'B' then 1 else 0 end),
  NullVal = sum(case when col1 = 'Null' then 1 else 0 end),
  count(col1) Total
from
(
  select 
    col1 = Isnull(col1, 'Null'), 
    col2 = isnull(cast(col2 as varchar(5)), 'Null'),
    col3
  from yourtable
) d
group by col2
with cube;

SQL Fiddle with Demo。这使用CASE表达式获取ABnullCol1值的总计,然后使用CUBE汇总总计。给出结果:

|  COL2 | A | B | NULLVAL | TOTAL |
|-------|---|---|---------|-------|
|     1 | 2 | 1 |       1 |     4 |
|     2 | 1 | 1 |       0 |     2 |
|  Null | 0 | 1 |       0 |     1 |
| Total | 3 | 3 |       1 |     7 |