有一个表,有3列id, start (timestamp), duration (interval)。此表显示了在线课程的开始时间和持续时间。问题是服务器不能同时支持三个以上的会议。我们需要一个请求来确定哪些广播或在什么时间相交,以便提前抓住它并重新安排计划的课程。例如,如果
中有广播15:00 for 45分钟
15:00 1小时
15:15 for 1 hour 15 minutes
15:30 for 45 minutes
我们看到一个交集,我们的服务器不会"处理",请求必须找到它并返回,例如,一个"坏"。这些课程的间隔或时间如何使用SQL解决这个问题?
create table lessons
(id bigserial not null constraint str_pkey primary key, duration interval, sch_at timestamp with time zone)
insert into lessons
(id, sch_at, duration) values
(1234, '2020-09-19 15:30:00.000000', '0 years 0 mons 0 days 1 hours 15 mins 0.00 secs'),
(1235, '2020-09-19 15:45:00.000000', '0 years 0 mons 0 days 0 hours 45 mins 0.00 secs');
谢谢!屏幕
您可以使用以下命令计算给定时间的并发会话数:
with t as (
select sch_at as ts, 1 as inc
from lessons t
union all
select sch_at + duration, -1 as inc
from lessons t
)
select t.*
from (select ts,
sum(sum(inc)) over (order by ts) as num_concurrent
from t
group by ts
) t
where num_concurrent > 3;
注意:这并不包括一个会话正好在另一个会话开始时结束的重叠。
这是一个db<>小提琴