寻找日期范围Postgres之间的差距

时间:2018-10-01 07:45:22

标签: postgresql gaps-and-islands

我有这张桌子,需要找出间隔之间的差距

记录可能重叠。

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

1 个答案:

答案 0 :(得分:3)

demo: db<>fiddle

您可以使用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中的保留字。您最好使用其他列名称。