GROUP BY并计算列是否为空

时间:2016-05-17 02:15:29

标签: sql sql-server sql-server-2012

我有一个执行GROUP BY (col1, col2, col3)的查询,然后将计数返回为groupByCount

+------+------+------+--------------+
| col1 | col2 | col3 | groupByCount |
+------+------+------+--------------+
|    1 | a    | A    |            2 |
|    2 | b    | B    |            4 |
|    1 | a    | null |            5 |
|    2 | b    | null |            3 |
+------+------+------+--------------+

这有效,但它并不完全是我所追求的。我想计算col3为null或不为null的位数:

+------+------+------+-------------+----------+
| col1 | col2 | col3 | col3notnull | col3null |
+------+------+------+-------------+----------+
|    1 | a    | A    |           2 |        5 |
|    2 | b    | B    |           4 |        3 |
|    1 | a    | null |           0 |        5 |
|    2 | b    | null |           0 |        3 |
+------+------+------+-------------+----------+

有没有办法执行此计数?

1 个答案:

答案 0 :(得分:2)

我认为您可以使用窗口函数执行此操作:

select col1, col2, col3,
       sum(case when col3 is not null then count(*) end) over (partition by col1, col2) as col3notnull,
       sum(case when col3 is null then count(*) end) over (partition by col1, col2) as col3null
from t
group by col1, col2, col3;

但是,我不明白为什么“not null”值为0但“null”值重复。

如果最后一列中的前两个值确实为0,那么:

select col1, col2, col3,
       (case when col3 is not null then count(*) else 0 end) as col3notnull,
       (case when col3 is null then count(*) else 0 end) as col3null
from t
group by col1, col2, col3;