DB2 按月分组并使用多个 where 子句计数

DB2 group by month and count with multiple where clauses

我有以下 DB2 table 命名为 INCIDENT

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

我没有得到什么概念?我认为这是可行的,但我不能全神贯注...

我明白了!当然,我在发布问题后想通了....

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')