时间间隔内滚动行数

Rolling count of rows withing time interval

为了进行分析,我需要根据创建时间聚合单个 table 的行。基本上,我想知道在当前订单之前的某个时间段内创建的订单数。似乎找不到解决方案。

Table结构:

order_id time_created
1 00:00
2 00:01
3 00:03
4 00:05
5 00:10

预期结果:

order_id count within 3 seconds
1 1
2 2
3 3
4 2
5 1

声音window functions 的应用程序。但是,遗憾的是,事实并非如此。 Window 帧只能基于行数,不能基于实际的列值。

使用 LEFT JOIN 的简单查询就可以完成这项工作:

SELECT t0.order_id
     , count(t1.time_created) AS count_within_3_sec
FROM   tbl      t0
LEFT   JOIN tbl t1 ON t1.time_created BETWEEN t0.time_created - interval '3 sec'
                                          AND t0.time_created
GROUP  BY 1
ORDER  BY 1;

db<>fiddle here

不适用于 time,就像在您的最小演示中一样,因为它不会环绕。我想假设 timestamptimestamptz.

是合理的

由于您将每一行本身都计入计数,因此 INNER JOIN 也可以。 (LEFT JOIN 面对可能的 NULL 值仍然更可靠。)

或者使用 LATERAL 子查询并且不需要在外部查询级别聚合:

SELECT t0.order_id
     , t1.count_within_3_sec
FROM   tbl t0
LEFT   JOIN LATERAL (
   SELECT count(*) AS count_within_3_sec
   FROM   tbl t1
   WHERE  t1.time_created BETWEEN t0.time_created - interval '3 sec'
                              AND t0.time_created
   ) t1 ON true
ORDER  BY 1;

相关:

对于大 tables 和时间范围内的许多行,遍历 table once 的过程解决方案将执行得更好。喜欢:

  • Window Functions or Common Table Expressions: count previous rows within range
  • GROUP BY and aggregate sequential numeric values