SQL MULTIPLE COUNTS,GROUP BY MONTHS

时间:2012-04-17 11:51:41

标签: sql db2

我有桌子:

STATUS  DEFECT   DATE

CLOSED  IP       01.01.2012 
CLOSED  TV       03.03.2012
CLOSED  ADSL     05.05.2012
CLOSED  ADSL     11.01.2012 
CLOSED  TV       15.01.2012
NEW     TV         
NEW     TV

我希望按月计算每个特定缺陷的计数。考虑的状态是CLOSED

我想成为的结果表:

MONTH     TV  ADSL  IP
January   1   1     1
March     1   0     0
May       0   1     0

我正在使用db2数据库,因此显示月份的部分是:

select case month(timestamp_iso(DATE))
        when 1 then 'January'
        when 2 then 'February'
        when 3 then 'March'
        when 4 then 'April'
        when 5 then 'May'
        when 6 then 'Jun'
        when 7 then 'July'
        when 8 then 'August'
        when 9 then 'September' 
        when 10 then 'October'
        when 11 then 'November'
        when 12 then 'December'
    end as Month

from TABLE
where  STATUS='CLOSED'
group by month(timestamp_iso(DATE))
order by month(timestamp_iso(DATE))

所以我只需要添加这部分来计算。谢谢

1 个答案:

答案 0 :(得分:3)

您可以使用另一个案例陈述来计算缺陷类别,该陈述会将计数限制在一个类别中的缺陷:

select case month(timestamp_iso(DATE))
        when 1 then 'January'
        when 2 then 'February'
        when 3 then 'March'
        when 4 then 'April'
        when 5 then 'May'
        when 6 then 'Jun'
        when 7 then 'July'
        when 8 then 'August'
        when 9 then 'September' 
        when 10 then 'October'
        when 11 then 'November'
        when 12 then 'December'
    end as Month,
    count (case when defect = 'TV' then 1 end) TV,
    count (case when defect = 'ADSL' then 1 end) ADSL,
    count (case when defect = 'IP' then 1 end) IP
from TABLE
where  STATUS='CLOSED'
group by month(timestamp_iso(DATE))
order by month(timestamp_iso(DATE))