PostgreSQL 中重叠间隔的最大计数

Maximum count of overlapping intervals in PostgreSQL

假设有一个table结构如下:

id    start      end
--------------------
01    00:18    00:23
02    00:22    00:31
03    00:23    00:48
04    00:23    00:39
05    00:24    00:25
06    00:24    00:31
07    00:24    00:38
08    00:25    00:37
09    00:26    00:42
10    00:31    00:34
11    00:33    00:38

objective 用于计算在任何给定时刻处于活动状态(即在 startend 之间)的总最大行数。使用程序算法这将相对简单,但我不确定如何在 SQL.

中执行此操作

根据以上示例,此最大值为 8,对应于 00:31 时间戳,其中活动行为 2、3、4、6、7、8、9、10(如图所示在下面的架构中)。

获取时间戳和最大值对应的活跃行并不重要,需要的只是实际值本身。

I was thinking of at first, using generate_series() to iterate every minute and get the count of active intervals for each, then take the max of this.

您可以改进您的想法并仅迭代 table 中的“开始”值,因为“开始”点之一包含在具有最大活动行的时间间隔内。

select id, start,
    (select count(1) from tbl t where tbl.start between t.start and t."end")
from tbl;

这里是结果

id  start   count
-----------------
1   00:18:00    1
2   00:22:00    2
3   00:23:00    4
4   00:23:00    4
5   00:24:00    6
6   00:24:00    6
7   00:24:00    6
8   00:25:00    7
9   00:26:00    7
10  00:31:00    8
11  00:33:00    7

因此,此查询为您提供了已激活的最大行数

select
    max((select count(1) from tbl t where tbl.start between t.start and t."end"))
from tbl;
max
-----
8