Skip to content
Advertisement

Returning non-overlapping records within a date range

I have the following data. I have looked over a lot of threads about overlapping and non-overlapping dates but none seemed to help me.

===============================
PK  | StartDate  |  EndDate
===============================
1   | 2016-05-01 |  2016-05-02
2   | 2016-05-02 |  2016-05-03
3   | 2016-05-03 |  2016-05-04
4   | 2016-05-04 |  2016-05-05
5   | 2016-05-07 |  2016-06-08
===============================

From this table with a SQL query I want to return the first record out of overlapping dates or basically

===============================
PK  | StartDate  |  EndDate
===============================
1   | 2016-05-01 |  2016-05-02
3   | 2016-05-03 |  2016-05-04
5   | 2016-05-07 |  2016-06-08
===============================

I have been struggling a lot with this query and was wondering if this is actually possible without too much of a hit on performance and whether its better if thats done on backend or with a SQL query because I believe it’d be easier for me to do it on the backend.

Advertisement

Answer

This can be achieved by creating a new column and partitioning it to fetch only first rows.

declare @tbl table
(pk int identity,StartDate date,EndDate date)

insert into @tbl
values('2016-05-01','2016-05-02')
,('2016-05-02','2016-05-03')
,('2016-05-03','2016-05-04')
,('2016-05-04','2016-05-05')
,('2016-05-07','2016-06-08')

select pk,startdate,enddate  from(select pk,startdate,enddate 
,ROW_NUMBER()over(partition by [overlappingdates] order by startdate)rn
from(
select *,case when ROW_NUMBER()over(order by startdate) % 2 = 0 
then StartDate else EndDate end as [overlappingdates]
from
@tbl
)t
)t
where t.rn = 1
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement