Sql 基于列值获取值
这是我的桌子:Sql 基于列值获取值,sql,postgresql-10,Sql,Postgresql 10,这是我的桌子: idMission Event Timestamp 1 detectedBubbleOut 2018-05-26T12:53:43.000Z 1 arrived 2018-05-26T13:58:57.000Z 1 detectedInBuilding 2018-05-26T12:42:20.000Z 1 detec
idMission Event Timestamp
1 detectedBubbleOut 2018-05-26T12:53:43.000Z
1 arrived 2018-05-26T13:58:57.000Z
1 detectedInBuilding 2018-05-26T12:42:20.000Z
1 detectedBubbleIn 2018-05-26T12:37:36.000Z
1 detectedTimeOut 2018-05-26T12:52:17.000Z
1 scanFulfilled 2018-05-26T12:41:26.000Z
1 detectedBubbleIn 2018-05-26T12:37:22.000Z
1 customerInteraction 2018-05-26T13:59:04.000Z
1 scanFulfilled 2018-05-26T13:59:01.000Z
1 delFulfilled 2018-05-26T12:48:30.000Z
1 eventFulfilled 2018-05-26T12:48:30.000Z
1 nextDelivery 2018-05-26T12:50:20.000Z
1 customerInteraction 2018-05-26T12:48:18.000Z
1 detectedOutBuilding 2018-05-26T12:49:21.000Z
1 arrived 2018-05-26T12:40:09.000Z
1 detectedTimeIn 2018-05-26T12:38:58.000Z
2 nextDelivery 2018-05-27T12:50:20.000Z
2 customerInteraction 2018-05-27T12:48:18.000Z
2 detectedOutBuilding 2018-05-27T12:49:21.000Z
2 arrived 2018-05-27T12:40:09.000Z
2 detectedTimeIn 2018-05-27T12:38:58.000Z
有些事件与时间戳关联,这是事件发生的时间。我主要关注事件“到达”和“detectedTimeIn”,但事件“detectedTimeIn”并不总是可用,所以我使用“到达”。
我只想根据特定事件获取时间戳。
如果事件“detectedTimeIn”存在,那么我获取它的时间戳,如果它不存在,那么我将获取事件“Arrized”的时间戳。
这就是我迄今为止所取得的成就:
select
event,
stp."timestamp" as TimeIN
from main_source_execevent_coop stp
where event Coalesce('detectedTimeIn', 'arrived')
预期成果:
1 detectedTimeIn 2018-05-26T12:38:58.000Z
2 arrived 2018-05-27T12:40:09.000Z
但它不起作用,我只得到:
1检测时间2018-05-26T12:38:58.000Z
忽略“到达”行。
你有什么建议吗
谢谢如果您正在查看“下一个”或“上一个”事件,请使用lead()
/lag()
:
试试这个:
SELECT * FROM
(SELECT event,
stp."timestamp" as TimeIN
FROM your_table
WHERE event ='detectedTimeIn'
LIMIT 1
UNION ALL
SELECT event,
stp."timestamp" as TimeIN
FROM your_table
WHERE event ='arrived'
LIMIT 1) a
LIMIT 1
编辑你的问题并展示你的预期结果。难道不是这样吗,你总是把它的第一个论点作为一个结果?问题不清楚。你有这个结果集的主键吗?我已经用我期望的结果和我得到的结果更新了这个问题。
SELECT * FROM
(SELECT event,
stp."timestamp" as TimeIN
FROM your_table
WHERE event ='detectedTimeIn'
LIMIT 1
UNION ALL
SELECT event,
stp."timestamp" as TimeIN
FROM your_table
WHERE event ='arrived'
LIMIT 1) a
LIMIT 1