2014-09-26 66 views
0

我嘗試將分組元素作爲列和計數作爲行元素。SQL分組和計數在一起

可能的狀態= IO,NIO,打開,關閉,取消
可能類型=類型A,類型B,typeC,鍵入

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 
+0

您正在使用的數據庫? – 2014-09-26 10:33:01

+0

你使用了什麼樣的SQL? – LukeH 2014-09-26 10:33:33

+0

@ AllanS.Hansen我使用Db2 DB ... – Kayser 2014-09-26 10:34:46

回答

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應該沒有問題地運行。

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