I have an events table that has a start and end date columns (events do not overlap), sample data
if object_id('tempdb..#SourceTable') is not null
begin
drop table #SourceTable
end
create table #SourceTable
(
Id int identity(1,1) not null,
WindowRange varchar(15) not null,
StartDatetime datetime null,
EndDatetime datetime null
)
insert into #SourceTable
(
WindowRange,
StartDatetime,
EndDatetime
)
values
('04:20 - 05:36', '2015-08-31 04:20:01.890', '2015-08-31 05:36:14.290' ),
('00:20 - 01:24', '2015-08-31 00:20:01.487', '2015-08-31 01:24:52.983' ),
('20:20 - 21:27', '2015-08-30 20:20:01.177', '2015-08-30 21:27:53.317' ),
('16:20 - 17:28', '2015-08-30 16:20:01.133', '2015-08-30 17:28:24.173' ),
('12:20 - 13:30', '2015-08-30 12:20:01.273', '2015-08-30 13:30:38.370' )
Sample Output
Id WindowRange StartDatetime EndDatetime
1 04:20 - 05:36 2015-08-31 04:20:01.890 2015-08-31 05:36:14.290
2 00:20 - 01:24 2015-08-31 00:20:01.487 2015-08-31 01:24:52.983
3 20:20 - 21:27 2015-08-30 20:20:01.177 2015-08-30 21:27:53.317
4 16:20 - 17:28 2015-08-30 16:20:01.133 2015-08-30 17:28:24.173
5 12:20 - 13:30 2015-08-30 12:20:01.273 2015-08-30 13:30:38.370
I would like to have additional rows that fill the gaps in the ranges, for the example above
Expected Output
Id WindowRange StartDatetime EndDatetime
1 04:20 - 05:36 2015-08-31 04:20:01.890 2015-08-31 05:36:14.290
2 01:24 - 04:20 2015-08-31 01:24:52.983 2015-08-31 04:20:01.890
3 00:20 - 01:24 2015-08-31 00:20:01.487 2015-08-31 01:24:52.983
4 00:00 - 00:20 2015-08-31 00:00:00.000 2015-08-31 00:20:01.487
5 21:27 - 23:59 2015-08-30 21:27:53.317 2015-08-30 23:59:59.999
6 20:20 - 21:27 2015-08-30 20:20:01.177 2015-08-30 21:27:53.317
7 17:28 - 20:20 2015-08-30 17:28:24.173 2015-08-30 20:20:01.177
8 16:20 - 17:28 2015-08-30 16:20:01.133 2015-08-30 17:28:24.173
9 13:30 - 16:20 2015-08-30 13:30:38.370 2015-08-30 16:20:01.133
10 12:20 - 13:30 2015-08-30 12:20:01.273 2015-08-30 13:30:38.370
I have tried using a common table expression with a window function but can't seem to get it right
;with myCTE as
(
select
row_number() over (order by EndDatetime desc) as SeqNo,
StartDatetime,
EndDatetime
from #SourceTable
)
select
t1.SeqNo as [T1SeqNo],
t2.SeqNo as [T2SeqNo],
t1.StartDatetime as [T1Start],
t1.EndDatetime as [T1End],
t2.StartDatetime as [T2Start],
t2.EndDatetime as [T2End]
from myCTE t1
left join myCTE t2
on t1.SeqNo = t2.SeqNo - 1
Any suggestion/help would be greatly appreciated.