使用PostgreSQL计算行和条件组之间的时差

使用PostgreSQL计算行和条件组之间的时差,sql,postgresql,datetime,group-by,lag,Sql,Postgresql,Datetime,Group By,Lag,我有如下数据: +-------+-------+ | index | time | +-------+-------+ | 1 | 09.00 | | 2 | 09.02 | | 3 | 09.03 | | 4 | 09.05 | | 5 | 09.11 | | 6 | 09.12 | | 7 | 09.15 | | 8 | 09.22 | | 9 | 09.33 | +-------+-------+ +------

我有如下数据:

+-------+-------+
| index | time  |
+-------+-------+
|     1 | 09.00 |
|     2 | 09.02 |
|     3 | 09.03 |
|     4 | 09.05 |
|     5 | 09.11 |
|     6 | 09.12 |
|     7 | 09.15 |
|     8 | 09.22 |
|     9 | 09.33 |
+-------+-------+
+-------+-------+
| index | time  |
+-------+-------+
|     1 | 09.00 |
|     1 | 09.02 |
|     1 | 09.03 |
|     1 | 09.05 |
|     2 | 09.11 |
|     2 | 09.12 |
|     2 | 09.15 |
|     3 | 09.22 |
|     4 | 09.33 |
+-------+-------+

如果行之间的时间差,则只需要一个累积和:

select t.*,
       count(*) filter (where prev_time < time - interval '5 minute') over (order by time) as index
from (select t.*,
             lag(time) over (order by time) as prev_time
      from t
     ) t;

是一个dbfiddle。

此查询有错误。。列t.index必须出现在GROUP BY子句中或在聚合中使用function@TheGreat . . . 我不明白这个错误。这是一个窗口函数,不需要聚合。Lindoff-你可以在这里引用数据库@TheGreat。这不是这个答案中的疑问。你遗漏了over条款。我在答案上加了一把小提琴。