SQL选择将来自多行的数据组合成一行

时间:2016-01-20 23:45:50

标签: sql sql-server-2008 report common-table-expression

我有一张类似于此的表格:

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

我想建立一个看起来像这样的报告(基本上每个OLD数据点获取TIME值):

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

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分: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;