我有两个表(table1和table2),我希望得到最终结果
有谁知道如何在SQL语法中获得此结果?
表1语法 SELECT actID,日期 FROM table1 ORDER BY actID ;
表2语法 SELECT动作,时间戳,时间 FROM table1 ORDER BY act,timestamp ;
endResult语法: ??
答案 0 :(得分:0)
最简单的方法是连接到表2四次,如下所示:
Select
t1.actID
, t1.date
, t25.time as t5
, t27.time as t7
, t28.time as t8
, t210.time as t10
From table1 as t1
left outer join table2 as t25
on t25.act = t1.actid
and t25.timestamp = 5
left outer join table2 as t27
on t27.act = t1.actid
and t27.timestamp = 7
left outer join table2 as t28
on t28.act = t1.actid
and t28.timestamp = 8
left outer join table2 as t210
on t210.act = t1.actid
and t210.timestamp = 10
有意义吗?
答案 1 :(得分:0)
我经常使用聚合来解决这个问题:
select t1.actid, t1.timestamp,
max(case when t2.timestamp = 5 then t2.time end) as time_5,
max(case when t2.timestamp = 7 then t2.time end) as time_7,
max(case when t2.timestamp = 8 then t2.time end) as time_8,
max(case when t2.timestamp = 10 then t2.time end) as time_10
from t1 left join
t2
on t1.actid = t2.act
group by t1.actid, t1.timestamp;