LAG功能和GROUP BY

jja*_*mes 22 postgresql

我有一张这样的桌子,

 event_id |          date          
----------+------------------------
  1703702 | 2013-06-25 07:50:57-04
  3197588 | 2013-06-25 07:51:57-04
 60894420 | 2013-06-25 07:52:57-04
 60894420 | 2013-06-25 07:53:57-04
   183503 | 2013-06-25 07:54:57-04
 63116743 | 2013-06-25 07:55:57-04
 63110451 | 2013-06-25 07:56:57-04
 63116743 | 2013-06-25 07:57:57-04
 63116743 | 2013-06-25 07:58:57-04
Run Code Online (Sandbox Code Playgroud)

我想应用滞后函数,但也是一个组,所以我可以找到任何特定event_id之间的时间间隔.

我想要这样的事情:

SELECT event_id, difference
FROM ( 
  SELECT event_id, date - lag(date) over (order by date) as
  difference FROM table GROUP BY event_id
) t;
Run Code Online (Sandbox Code Playgroud)

但是我不能将GROUP BY与LAG功能一起使用.我想要一个类似于以下的结果:

63116743, {120, 60}
60894420, {60}
...
...
Run Code Online (Sandbox Code Playgroud)

因此,第一个id的事件之间有一个120s和60s的窗口,第二个id的60s窗口.

有没有办法做到这一点?输出格式不是太重要,只要我最终可以将它放入数组中.我正在使用Postgres 9.1

小智 29

WITH diffs as (
    SELECT
        event_id,
        date - lag(date) over (partition BY event_id ORDER BY date) as difference
    FROM
        TABLE
)
SELECT
    event_id,
    array_agg( difference ) as all_diffs
FROM
    diffs
GROUP BY event_id;
Run Code Online (Sandbox Code Playgroud)

应该管用.