如何使用开始和结束日期时间在 Driver 的行程中查找重叠记录
How to find the overlapping records in a Trips made from a Driver using Start and End Date Time
我有一个如下所示的行程数据集,其中我有给定 drivers 及其相关车辆及其开始和结束日期时间的行程。
Data Set
从上面可以看出,我的行程记录之间的开始日期时间和结束日期时间之间存在重叠。
Processed Data Set
这意味着 Driver 在任何给定时间旅行或旅行不止一次,这是不可能的,因为单个 driver 可以在给定时间驾驶一辆车。
所以,我想从数据集中提取它们,留下 non-overlapping 或如下正确的。
Final Requirement
能否请您建议 SQL 满足上述要求。
此致,
达山 MS
我使用临时 table cte 来收集每个 driver 重叠的所有 tripID。然后我会用这些tripID加入原来的table。见下文并在此处示例:http://sqlfiddle.com/#!18/236dd/3
with cte as (
select t1.tripID as ID1,
t2.tripID as ID2
from yourTable t1
join yourTable t2
on t1.driverid=t2.driverid
where t1.startdatetime between t2.startdatetime and t2.enddatetime
and t1.tripID > t2.tripID)
select distinct tripID,
driverid,
vehicleid,
startdatetime,
enddatetime
from yourTable t, cte
where t.tripId = cte.ID1
or t.tripId = cte.ID2
我有一个如下所示的行程数据集,其中我有给定 drivers 及其相关车辆及其开始和结束日期时间的行程。
Data Set
从上面可以看出,我的行程记录之间的开始日期时间和结束日期时间之间存在重叠。
Processed Data Set
这意味着 Driver 在任何给定时间旅行或旅行不止一次,这是不可能的,因为单个 driver 可以在给定时间驾驶一辆车。
所以,我想从数据集中提取它们,留下 non-overlapping 或如下正确的。
Final Requirement
能否请您建议 SQL 满足上述要求。
此致, 达山 MS
我使用临时 table cte 来收集每个 driver 重叠的所有 tripID。然后我会用这些tripID加入原来的table。见下文并在此处示例:http://sqlfiddle.com/#!18/236dd/3
with cte as (
select t1.tripID as ID1,
t2.tripID as ID2
from yourTable t1
join yourTable t2
on t1.driverid=t2.driverid
where t1.startdatetime between t2.startdatetime and t2.enddatetime
and t1.tripID > t2.tripID)
select distinct tripID,
driverid,
vehicleid,
startdatetime,
enddatetime
from yourTable t, cte
where t.tripId = cte.ID1
or t.tripId = cte.ID2