I\'ve a table, which describes work slices of a business working calendar: (date format is 24 hours format)
PK | STARTDATE | ENDDATE
______________
Here's an example using SQL Server syntax. First it determines the "heads", or rows that have no previous overlapping rows. To determine the last "child" of a "head", it looks for the last row that is smaller than the next "head". Here's the SQL:
; with heads as
(
select row_number() over (order by head.StartDate) as PK
, *
from YourTable head
where not exists
(
select *
from YourTable prev
where prev.StartDate < head.StartDate
and head.StartDate < prev.EndDate
)
)
select row_number() over (order by h.StartDate) as PK
, h.StartDate
, max(yt.EndDate) as EndDate
from heads h
left join
heads nh
on nh.PK = h.PK + 1
left join
YourTable yt
on h.StartDate <= yt.StartDate
and (yt.StartDate < nh.StartDate or nh.StartDate is null)
group by
h.StartDate
Live example at SQL Fiddle.