2016-01-20 70 views
0

我有一個表,看起來與此類似:SQL選擇多行數據合併到一個單一的排

ID OLD  NEW  TIME 
1  a  b  5 
1  b  c  7 
1  c  d  45 
1  d  e  4 
2  a  b  1 
2  b  d  8 
2  d  e  45 
3  b  c  15 
3  c  d  14 

而且我想建立一個報告看起來像這樣的(基本上每個舊數據點搶時間價值):

ID TimeForA TimeForB TimeForC TimeForD  
1  5   7   45   4 
2  1   8   NULL  45 
3  NULL  15  14   NULL 

我已經能夠得到所有的數據到正確的列,但一直沒能到每一行合併爲一個單獨的行,每個ID。我目前的查詢看起來像這樣(不,我沒有每個專欄到位,仍然只是測試):

WITH CTE (id, ATime, BTime) 
AS 
(
    select T1.oid, T1.loggedFor, null, T1.time as Atime 
    from Table1 T1 
    where T1.OLD = 'a' 
    union 
    select T1.oid, T1.loggedFor, T1.time as BTime, null 
    from Table1 T1 
    where T1.old = 'b' 
) 
select ID, ATime, BTime 
from CTE 
order by ID 

任何幫助讚賞!

+0

請標記正在使用的數據庫。 –

+0

添加了SQL Server 2008標記,我的錯誤。 – user1161505

回答

0

試試這個:

select id, 
    sum(if(old = 'a',time,null)) as time_for_a, 
    sum(if(old = 'b',time,null)) as time_for_b, 
    sum(if(old = 'c',time,null)) as time_for_c, 
    sum(if(old = 'd',time,null)) as time_for_d 
from test_tbl 
group by id 
order by id; 
+0

謝謝,這很有幫助! – user1161505