我有这张桌子,需要找出间隔之间的差距
记录可能重叠。
user | start_time | end_time
user1|2018-09-26T02:16:52.023453|2018-09-26T03:12:04.404477
user1|2018-09-25T22:15:49.593296|2018-09-26T00:15:52.016497
user1|2018-09-25T20:13:02.358192|2018-09-25T22:15:49.593296
预期输出将为
user | start_time | end_time
user1|2018-09-26T00:15:52.016497|2018-09-26T02:16:52.023453
答案 0 :(得分:3)
您可以使用lag
窗口功能(https://www.postgresql.org/docs/current/static/tutorial-window.html)。此函数将值从上一行移到当前行。现在可以将移动end_time
与当前start_time
进行比较,并检查差距。
SELECT
"user",
prev_end_time as gap_start_time,
start_time as gap_end_time
FROM (
SELECT
*,
lag(end_time) OVER (PARTITION BY "user" ORDER BY start_time) as prev_end_time
FROM time_intervals
ORDER BY start_time
) s
WHERE start_time > prev_end_time
结果
user gap_start_time gap_end_time
user1 2018-09-26 00:15:52.016497 2018-09-26 02:16:52.023453
请注意,“用户”是Postgres中的保留字。您最好使用其他列名称。