计算几个用户之间在SQL中的重叠时间间隔

时间:2018-11-14 20:40:27

标签: sql postgresql postgresql-9.5

花了很多时间在网上寻找答案后,我决定将其发布在这里。

我有一个表,其中包含一些资源不可用的时间间隔。我想提取所有资源都不可用的所有时间间隔。

在下面的示例中,我将有:开始:2018-11-16 12:30:00,结束:2018-11-16 12:45:00

Start                   End                     Resource
-------------------     -------------------     ----------  
2018-11-15 12:00:00     2018-11-15 13:00:00     resource A
2018-11-15 12:00:00     2018-11-15 13:00:00     resource B
2018-11-15 12:30:00     2018-11-15 14:00:00     resource C
2018-11-15 12:00:00     2018-11-15 12:45:00     resource D
2018-11-18 12:00:00     2018-11-18 13:00:00     resource A
2018-11-19 11:40:00     2018-11-19 12:20:00     resource B
2018-11-15 16:00:00     2018-11-15 17:00:00     resource D

有人有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您知道资源数量(或可以计算得出),并且资源的起始/结束范围没有重叠(即您获得了干净的数据):

select Start, "End"
from
 ( -- calculate a Cumulative Sum to get the count of resources unavailable at any point in time
   select Start,
      lead(Start) over (order by Start,  x) as "End", 
      sum(x) over (order by Start,  x rows unbounded preceding) as cnt
   from
    ( -- combine starts & ends into a single table and assigne +/-1 to each row
      select Start,  1 as x
      from tab
      union all 
      select "End", -1 as x
      from tab
    ) as dt
 ) as dt
where cnt = 4 -- find the row where all resources are unavailable
--  where cnt = (select count(*) from resources)