SQL分组和计数在一起

时间:2014-09-26 10:30:32

标签: sql db2 db2-9.7

我尝试将分组元素作为列,将计数作为行元素。

可能的状态= IO,NIO,OPEN,CLOSED,CANCELED
可能的类型= TypeA,TypeB,typeC,typeD

MyTable (date, status, type, count)

2014-06-27,OPEN,typeA, 1
2014-07-01,OPEN,typeA, 1
2014-07-02,IO,typeB, 2
2014-07-02,IO,typeC, 3
2014-07-02,NIO,typeC, 4

结果应该是这样的。 (按日期和状态分组)

date,status,typeA_Count, typeB_Count, typeC_Count, typeD_Count

2014-06-27,OPEN,1, 0, 0, 0
2014-07-01,OPEN,1, 0, 0, 0
2014-07-02,IO, 0, 2, 3, 0
2014-07-02,NIO, 0, 0, 4, 0

2 个答案:

答案 0 :(得分:3)

一种简单的方法是使用CASE/GROUP BY来添加值;

SELECT "date", "status",
  SUM(CASE WHEN "type"='typeA' THEN "count" ELSE 0 END) typeA_count,
  SUM(CASE WHEN "type"='typeB' THEN "count" ELSE 0 END) typeB_count,
  SUM(CASE WHEN "type"='typeC' THEN "count" ELSE 0 END) typeC_count,
  SUM(CASE WHEN "type"='typeD' THEN "count" ELSE 0 END) typeD_count
FROM mytable
GROUP BY "date", "status"
ORDER BY "date", "status"

An Oracle SQLfiddle to test with,尽管DB2应该没有问题地运行。

答案 1 :(得分:0)

DB2不支持PIVOT子句,因此请尝试:

select date
     , status
     , sum(decode(type,'typeA',count,0)) as count_typeA
     , sum(decode(type,'typeB',count,0)) as count_typeB
     , sum(decode(type,'typeC',count,0)) as count_typeC
     , sum(decode(type,'typeD',count,0)) as count_typeD
  from mytable
 group by date, status