mysql - SQL 选择重叠行
问题描述
我得到了这个表操作:
+-----------+---------------------+----------+
| theatreNo | startDateTime | duration |
+-----------+---------------------+----------+
| 1 | 2019-05-12 09:30:00 | 04:50:00 |
| 3 | 2019-05-17 15:05:00 | 02:00:00 |
| 3 | 2019-05-17 16:05:00 | 03:00:00 |
+-----------+---------------------+----------+
而且我正在尝试查找我们是否有两个操作重叠的剧院,它应该输出以下内容:
+--------+---------------+----------+----------+
| roomNo | startDateTime | firstOp | secondOp |
+--------+---------------+----------+----------+
| 3 | 2019-05-17 | 15:05:00 | 16:05:00 |
+--------+---------------+----------+----------+
这是重叠的,因为一个手术从 15:05 开始,持续时间为 2 小时,而同一剧院的另一个手术从 16:05 开始,但第一个手术尚未完成。
我不知道是否有某种方法可以计算开始时间和持续时间之间的差异,并将其与下一个操作的开始时间进行比较。
解决方案
You can use join
to get pairs of overlaps in the same row:
select o.*, o2.*
from operation o join
operation o2
on o2.theatreNo = o.theatreNo and
o2.startDateTime < o.startDateTime + o.duration and
o2.startDateTime + o2.duration > o.startDateTime and
(o2.startDateTime <> o.startDateTime or
o2.duration <> o.duration
);
The logic gets much harder if you want to summarize the overlaps. The issue is that multiple time periods could overlap. You can get any pair in the same row -- but that pair might overlap with another, so there would be redundancy.
推荐阅读
- jquery - 过滤后Jquery插件数据表消失
- sql-server - 在 TSQL 中写 SELECT 'a' colName 是有效的,PL/SQL 中的替代是什么?
- html - 如何快速将引导按钮转换为 png 图像文件?
- postgresql - EF Core 2.0 更新 - 跟踪问题
- c++ - 在 Visual c++ 中使用 WebRTC 库
- r - 遵循模式时按名称获取列索引
- python - 如何使用 python 获取 FTP 的当前工作目录
- javascript - this.props.history.router 不适用于 websocket 的第一个触发器
- dart - 如何在 Fluro 或 Flutter 路由导航器中传递对象或对象列表?
- visual-studio-code - 我正在使用 PyGame 在 python3.6.5 中创建蛇游戏。这是初始代码,它在 PyCharm 上运行良好。但是我在 VSCode 中遇到了问题