[英]How to get multiple row items as different column in one sqlite command
我有一张桌子看起来像这样:
Timestamp direction John Mary car airplan
4960 1 1 null 1 null
5960 2 1 1 null 1
6960 1 null null 1 1
7960 1 1 null null 1
8960 2 1 null null null
记录的意思是:john / mary / together在时间戳记乘汽车/飞机返回xxx,我希望有一个单独的sqlite查询来获得如下结果:
John_t Mary_t car_t airplan_t
0 0 6960 7960
8960 5960 0 0
这表示(约翰,玛丽,汽车,飞机计划) (往/返)到xxx的最新时间戳。
我尝试sql命令,但是失败了...
select
(case when John=1 then max(Timestamp) else 0 end) as John_t,
(case when Mary=1 then max(Timestamp) else 0 end) as Mary_t,
(case when car=1 then max(Timestamp) else 0 end) as car_t,
(case when airplan=1 then max(Time) else 0 end) as airplan_t
from table where 4960 < Time < 8960 and group by direction
有人可以帮忙吗?
select John_t, Mary_t, car_t, airplan_t from
-- John --
(select direction, (case when Timestamp=max_Timestamp then Timestamp else 0 end) as John_t from
(
(select dir.direction as direction, max(Timestamp) as Timestamp from
(select distinct direction from trips) as dir
left outer join
(select * from trips where John = 1) as t
on dir.direction = t.direction
group by direction
)
cross join
(select max(Timestamp) as max_Timestamp from trips where John = 1)
)
)
natural join
-- Mary --
(select direction, (case when Timestamp=max_Timestamp then Timestamp else 0 end) as Mary_t from
(
(select dir.direction as direction, max(Timestamp) as Timestamp from
(select distinct direction from trips) as dir
left outer join
(select * from trips where Mary = 1) as t
on dir.direction = t.direction
group by direction
)
cross join
(select max(Timestamp) as max_Timestamp from trips where Mary = 1)
)
)
natural join
-- car --
(select direction, (case when Timestamp=max_Timestamp then Timestamp else 0 end) as car_t from
(
(select dir.direction as direction, max(Timestamp) as Timestamp from
(select distinct direction from trips) as dir
left outer join
(select * from trips where car = 1) as t
on dir.direction = t.direction
group by direction
)
cross join
(select max(Timestamp) as max_Timestamp from trips where car = 1)
)
)
natural join
-- airplan --
(select direction, (case when Timestamp=max_Timestamp then Timestamp else 0 end) as airplan_t from
(
(select dir.direction as direction, max(Timestamp) as Timestamp from
(select distinct direction from trips) as dir
left outer join
(select * from trips where airplan = 1) as t
on dir.direction = t.direction
group by direction
)
cross join
(select max(Timestamp) as max_Timestamp from trips where airplan = 1)
)
)
;
left outer join
所有可能的方向进行left outer join
联接。 这样可以确保每个约翰,玛丽,汽车和飞机计划的每个方向都有一行。 即使在该方向上没有“行程”,也需要稍后填写0
。 group by direction
max(Timestamp)
的最大时间戳( max(Timestamp)
),因为我们对同一方向上的较早行程不感兴趣。 将结果与John / Mary / car / airplan的整体最大时间戳交叉连接,以允许将较低的时间戳替换为0
使用
(case when Timestamp=max_Timestamp then Timestamp else 0)
我们为约翰,玛丽,汽车和飞机计划的每一个人做到这一点,并最终natural join
一切融合在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.