【问题标题】:How to get all non-overlapping time intervals in postgresql?如何在postgresql中获取所有不重叠的时间间隔?
【发布时间】:2022-02-22 11:27:05
【问题描述】:

我想生成两次之间没有约会的时间间隔。更具体地说,当某人在某个时间间隔内有空时。

例如,如果我检查谁在下午 1:30 到 3:30 之间有空,而 Doctor1 的预约时间是下午 1:15 到 2:00,而 Doctor2 的预约时间是下午 2:30 到 3:30,预计输出应该是:expected output

有谁知道我怎么能做到这一点? 我有一个约会表(包括 AppointmentDate、StartTime、EndTime、DoctorName 等)

非常感谢!

【问题讨论】:

  • Doctor1 不是在 2:00 - 3:30 也有空吗?
  • @Kosh 哦,是的,我相信它在预期的输出图像中,第 2 行
  • 对,对不起我的失明 =))
  • 简单。将 PostgreSQL v14 与多范围和减法一起使用。
  • 样本数据最好显示为formatted text。请参阅here,了解有关如何创建漂亮表格的一些提示。

标签: sql postgresql time


【解决方案1】:

假设您必须检查间隔[IntervalStart], [IntervalEnd]。那么:

select
  Name,
  ifnull(
    (
      select EndTime from Appointments
      where
        Name = A.Name and
        EndTime between [IntervalStart] and A.StartTime
        order by EndTime desc
        limit 1
     ),
     [IntervalStart]
  ) as StartTime,
  StartTime as EndTime
from Appointments
where 
  StartTime between [IntervalStart] and [IntervalEnd]
union select
  Name,
  EndTime as StartTime,
  ifnull(
    (
      select StartTime from Appointments
      where
        Name = A.Name and
        StartTime between A.EndtTime and [IntervalEnd]
        order by StartTime
        limit 1
     ),
     [IntervalEnd]
  ) as EndTime
from Appointments
where
  EndTime between [IntervalStart] and [IntervalEnd]
order by Name, StartTime;

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2016-04-12
    • 2021-06-18
    • 1970-01-01
    • 2013-10-16
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多