SQL select 将多行数据合并为一行

SQL select combine data from multiple rows into a single row

我有一个 table 看起来类似于:

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

我想构建一个如下所示的报告(基本上为每个旧数据点获取 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

感谢任何帮助!

试试这个:

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;