如何消除SQL中的重叠日期范围?

时间:2016-11-16 18:46:48

标签: sql-server tsql

我正在尝试消除数据集中的重叠日期范围。我将使用的数据集较小:

enter image description here

我如何消除突出显示的第一行数据,因为它与该特定ID的其他日期范围重叠?

由于

1 个答案:

答案 0 :(得分:0)

这是一个让您入门的基本方法,因为您不熟悉SO。毫无疑问,你需要改变你归类为重叠的逻辑。

--your test data...
declare @table table (ID int, BeginTime datetime, EndTime datetime)
insert into @table (ID, BeginTime, EndTime) VALUES
(101,'7/4/2016','9/21/2016'),
(101,'8/8/2016','9/8/2016'),
(101,'9/8/2016','9/21/2016'),
(102,'9/2/2016','9/7/2016'),
(103,'9/22/2016','9/28/2016'),
(103,'9/23/2016','9/28/2016')

/*
In SQL 2012 onward use LEAD and LAG to compare rows to the ones above or below them

Change this logic as you need... based on the limited information for "overlapping" 
I just placed a flag where the dates didn't light up perfectly. There are undoubtedly
more cases / better logic you will need.
*/

select 
    ID,
    BeginTime,
    EndTime,
    case when lead(BeginTime) over (partition by ID order by BeginTime asc) <> EndTime then 'n' else 'y' end as toKeep
from @table


--This is the same logic applied in a CTE so we can update the table

;with cte as(
    select 
        ID,
        BeginTime,
        EndTime,
        case when lead(BeginTime) over (partition by ID order by BeginTime asc) <> EndTime then 'n' else 'y' end as toKeep
    from @table)

--Update your table via the CTE

delete from cte where toKeep = 'n'
select * from @table