How to group timestamps into islands (based on arbitrary gap)?

后端 未结 2 2024
我在风中等你
我在风中等你 2021-01-22 16:08

Consider this list of dates as timestamptz:

I grouped the dates by hand using colors: every group is separated from the next by a gap of at least 2

2条回答
  •  死守一世寂寞
    2021-01-22 16:29

    This would do it:

    SELECT done, count(*) FILTER (WHERE step) OVER (ORDER BY done) AS grp
    FROM  (
       SELECT done
           , (lag(done) OVER (ORDER BY done) <= done - interval '2 min') AS step
       FROM   tbl
       ) sub
    ORDER  BY done;
    

    The subquery sub records step as true if the previous row is at least 2 min away - sorted by the timestamp column done itself in this case.

    The outer query adds a rolling count of steps, effectively the group number (grp) - combining the aggregate FILTER clause with another window function.

    db<>fiddle here

    Related:

    • Query to find all timestamps more than a certain interval apart
    • How to label groups in postgresql when group belonging depends on the preceding line?
    • Select longest continuous sequence
    • Grouping or Window

    About the aggregate FILTER clause:

    • How can I simplify this game statistics query?
    • Conditional lead/lag function PostgreSQL?

提交回复
热议问题