根据重叠的日期和时间创建一个Y / N标志列

问题描述

我正在尝试创建一个重叠列,以指示特定日期的时间是否存在重叠。该示例适用于一天中从事多项任务/工作的个人。我正在努力使OVERLAP_FLAG列正确填充。我正在使用12C Oracle数据库,但尝试了LEAD,LAG和Partition均未成功。在该示例中,所有行应具有的已计算OVERLAP_FLAG为“ Y”

enter image description here

CREATE "TEST1" (
    "NAME" VARCHAR2(26 BYTE),"JOB" VARCHAR2(26 BYTE),"START_TIME" DATE,"STOP_TIME" DATE,"OVERLAP_FLAG" VARCHAR2(26 BYTE)
);  

Insert into TEST1 (NAME,JOB,START_TIME,STOP_TIME,OVERLAP_FLAG) values ('JOE ','A02',to_date('18-AUG-2020 09.22.31','DD-MON-YYYY HH24.MI.SS'),to_date('18-AUG-2020 15.59.12','Y');
Insert into TEST1 (NAME,'A01',to_date('18-AUG-2020 09.22.35',to_date('18-AUG-2020 15.58.55','B01',to_date('18-AUG-2020 09.22.43',to_date('18-AUG-2020 15.58.32','B02',to_date('18-AUG-2020 09.22.49',to_date('18-AUG-2020 15.58.45','C02',to_date('18-AUG-2020 09.22.56',to_date('18-AUG-2020 15.58.20','C01',to_date('18-AUG-2020 09.23.04',to_date('18-AUG-2020 15.58.08','X01',to_date('18-AUG-2020 15.57.02',to_date('18-AUG-2020 15.57.03','Y01',to_date('18-AUG-2020 15.57.11',to_date('18-AUG-2020 15.57.12','Z01',to_date('18-AUG-2020 15.57.30',to_date('18-AUG-2020 15.57.31','W01',to_date('18-AUG-2020 15.57.47',to_date('18-AUG-2020 15.57.48','Y');

解决方法

一个选项使用exists和一个case表达式:

select
    t.*,case when exists (
        select 1
        from test1 t1
        where 
            t1.name = t.name
            and t1.job <> t.job
            and t1.start_time < t.stop_time
            and t1.stop_time  > t.start_time
    ) then 'Y' else 'N' end overlap_flag
from test1 t

子查询的谓词描述的记录具有相同的name,不同的job和重叠的日期范围。

Demo on DB Fiddlde