在Postgres中分组事件

时间:2017-02-22 23:02:40

标签: postgresql aggregate-functions gaps-and-islands

我有一个由网站上的用户活动生成的事件表:

timestamp | name
7:00 AM   | ...
7:01 AM   | ...
7:02 AM   | ...
7:30 AM   | ...
7:31 AM   | ...
7:32 AM   | ...
8:01 AM   | ...
8:03 AM   | ...
8:05 AM   | ...
8:08 AM   | ...
8:09 AM   | ...

我想聚合事件,以提供用户何时处于活动状态的视图。我将活动定义为表示事件在+/- 2分钟内的时间段。对于上述那个意思是:

from    | till
7:00 AM | 7:02 AM
7:30 AM | 7:32 AM
8:01 AM | 8:05 AM
8:08 AM | 8:09 AM

编写将在该方法中聚合的查询的最佳方法是什么?是可以通过WINDOW函数或自联接还是需要PL / SQL?

2 个答案:

答案 0 :(得分:1)

使用两个窗口函数:一个用于计算连续事件(间隙)之间的间隔,另一个用于查找小于或等于2分钟的一系列间隙:

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.

答案 1 :(得分:0)

通过将它们分组在半小时的地板上并获得最小值和最小值。最大值:

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;

您可以使用日期时间值应用相同的收据,例如:

WITH x(t) AS (
   SELECT '2017-01-01'::TIMESTAMP + (RANDOM()*1440*'1 minute'::INTERVAL) t
   FROM GENERATE_SERIES(0,1000))
SELECT MIN...