2016-05-17 70 views
1

我已經得到了執行GROUP BY (col1, col2, col3)查詢,然後返回計數爲groupByCountGROUP BY和計數列是否爲空

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

這樣的作品,但它不完全是我後。我想吻合的地方COL3是空的計數或NOT 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 | 
+------+------+------+-------------+----------+ 

是否有執行該計數的方法嗎?

回答

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; 

不過,我不明白爲什麼「不空」的值是0,但「空」值重複。

如果在最後一列的前兩個值確實應該爲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;