2015-02-05 101 views
0

我有以下名爲DB2表事故DB2組和多個計數where子句

ticketid  Createdon  Severity 
1   2012-01-01 1 
2   2012-01-10 2 
3   2012-01-15 2 
4   2012-01-20 3 
5   2012-01-29 3 
6   2012-02-06 3 
7   2012-02-15 3 
8   2012-02-20 3 
9   2012-02-20 4 
10   2012-02-21 3 

我試圖在成果方面獲得:

Month  Sev1 Sev2 Sev3 Sev4 
==================================== 
2012-01  1  2  2  0 
2012-02  0  0  4  1 

到目前爲止,我有這樣的:

select to_char(INCIDENT.CREATEDON, 'YYYY-MM') as month, 
count(case when severity = 1 then 1 else 0 end) as SEV1, 
count(case when severity = 2 then 1 else 0 end) as SEV2 
from INCIDENT group by to_char(INCIDENT.CREATEDON,'YYYY-MM') 

但是,讓我所有的事故兩列...

Month  Sev1 Sev2 Sev3 Sev4 
==================================== 
2012-01  11  11  11  11 
2012-02  16  16  16  16 

我沒有得到什麼概念?我會認爲這是可行的,但不能把我的頭繞在這...

回答

1

我明白了!當然我在發佈我的問題後想通了......

select to_char(INCIDENT.CREATEDON, 'YYYY-MM') as month, 
sum(case when severity = 1 then 1 else 0 end) as sev1, 
sum(case when severity = 2 then 1 else 0 end) as sev2, 
sum(case when severity = 3 then 1 else 0 end) as sev3, 
sum(case when severity = 4 then 1 else 0 end) as sev4 
from INCIDENT 
where (createdon >= current_timestamp - (minute(current_timestamp) minute) - (hour(current_timestamp) -1) hours - (day(current_date) - 1) days - 13 month) group by to_char(INCIDENT.CREATEDON,'YYYY-MM')