Grouping Events in Postgres

戏子无情 提交于 2019-12-06 15:19:18

Use two window functions: one to calculate intervals between contiguous events (gaps) and another to find series of gaps less or equal 2 minutes:

select arr[1] as "from", arr[cardinality(arr)] as "till"
from (  
    select array_agg(timestamp order by timestamp)  arr
    from (
        select timestamp, sum((gap > '2m' )::int) over w
        from (
            select timestamp, coalesce(timestamp - lag(timestamp) over w, '3m') gap
            from events
            window w as (order by timestamp)
            ) s
        window w as (order by timestamp)
        ) s
    group by sum
    ) s

   from   |   till   
----------+----------
 07:00:00 | 07:02:00
 07:30:00 | 07:32:00
 08:01:00 | 08:05:00
(3 rows)        

Test it here.

By grouping them around half-hour flooring and getting min & max values:

WITH x(t) AS ( VALUES
('7:02 AM'::TIME),('7:01 AM'::TIME),('7:00 AM'::TIME),
('7:30 AM'::TIME),('7:31 AM'::TIME),('7:32 AM'::TIME),
('8:01 AM'::TIME),('8:03 AM'::TIME),('8:05 AM'::TIME)
)   
SELECT MIN(t) "from", MAX(t) "till"
   FROM (select t, date_trunc('hour', t) +
      CASE WHEN (t-date_trunc('hour', t)) >= '30 minutes'::interval
      THEN '30 minutes'::interval ELSE '0'::interval END t1 FROM x ) y
   GROUP BY t1 ORDER BY t1;

You can apply the same receipt with datetime values like:

WITH x(t) AS (
   SELECT '2017-01-01'::TIMESTAMP + (RANDOM()*1440*'1 minute'::INTERVAL) t
   FROM GENERATE_SERIES(0,1000))
SELECT MIN...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!