这是我的桌子
Event Time Order Mission TimeStamp
arrived 14:50 281475024521271 281475024568005 2017-08-09 14:50:59
nextDelivery 14:51 281475024521271 281475024568005 2017-08-09 14:51:33
arrived 15:27 281475024521271 281475024568005 2017-08-09 15:27:13
nextDelivery 15:28 281475024521271 281475024568005 2017-08-09 15:28:04
这是我的查询:
with times as(
select
event,
to_char("timestamp"::timestamptz at time zone 'Europe/Rome', 'HH24:MI') as Time,
orders,
mission,
"timestamp"::timestamptz at time zone 'Europe/Rome' as TimeStamp
from main_source_execevent
where orders = '281475024521271'
and event in ('arrived', 'nextDelivery')
order by "timestamp"
)
select
case when event = 'arrived' then time end as TimeIN,
case when event = 'nextDelivery' then time end as TimeOUT,
orders
from Times
查询结果为:
TimeIN TimeOut Order
14:50 NULL 281475024521271
NULL 14:51 281475024521271
15:27 NULL 281475024521271
NULL 15:28 281475024521271
我要实现的是将订单的timein和timeout放在同一行上。 我不知道如何获得这个结果。 你能帮我吗?
所需结果:
TimeIN TimeOut Order
14:50 14:51 281475024521271
15:27 15:28 281475024521271
编辑:添加的信息
联接应该在到达和下一个传递之间使用最接近的时间戳,以便如预期结果中所述,只能有一对timein / timeout。
答案 0 :(得分:2)
注意:这将回答问题的原始版本,而不是新的扩展版本。尽管这只是部分答案,但我会一直坚持下去,直到添加一个更好的答案为止。
在联接条件包含“超时”事件的值时使用自我联接,并将主表限制为“超时”事件:
select tin."order",
tin."timestamp" as time_in,
tout."timestamp" as time_out
from main_source_execevent tin
left join main_source_execevent tout on tin."order" = tout."order" and tout.event = 'nextDelivery'
where tin.event = 'arrived'
and tin.order = 281475024521271
在线示例:http://rextester.com/QMZO32570
使用("order", event)
上的索引,这应该非常有效
答案 1 :(得分:0)
我认为顺序和任务价值很重要,并且加入的双方都应该相等。区别于返回第一行以获取括号内各列的唯一值。 如果您删除“ and mse1.order = 281475024521271”行,并将返回所有订单/任务的结果
select distinct on (mse1.order, mse1.timestamp)
mse1.timestamp time_in,
max(mse2.timestamp) time_out,
mse1.order
from main_source_execevent mse1
main_source_execevent mse2
where mse1.order = mse2.order
and mse1.mission = mse2.mission
and mse1.event = 'arrived'
and mse2.event = 'nextDelivery'
and mse1.order = 281475024521271
order by mse1.order, mse1.timestamp, mse2.timestamp