With Shifts As
(
Select 1 As Num
, Cast('2012-05-01 6:00 AM' As datetime) As ShiftStart
, DateAdd(hh,12,Cast('2012-05-01 6:00 AM' As datetime)) As ShiftEnd
Union All
Select Num + 1, ShiftEnd, DateAdd(hh,12,ShiftEnd)
From Shifts
Where ShiftEnd < '2012-05-30'
)
, Segments As
(
Select event_id
, Case
When Shifts.ShiftStart > event_start Then Shifts.ShiftStart
Else event_start
End As start_split_segment
, Case
When Shifts.ShiftEnd < event_end Then Shifts.ShiftEnd
Else event_end
End As end_split_segment
, Count(*) Over ( Partition By E.event_id ) As SegmentCount
From events As E
Join Shifts
On E.event_start <= ShiftEnd
And E.event_end > ShiftStart
)
Select E.event_id, E.description, E.event_start, E.event_end
, S.start_split_segment, S.end_split_segment
, Case When SegmentCount > 1 Then 1 Else 0 End As is_split
, NullIf(SegmentCount,1) As split_segments
From Segments As S
Join events As E
On E.event_id = S.event_id
SQLフィドルバージョン
このソリューションでは、すべてのシフトの開始日と終了日のカレンダーを生成しました。Where ShiftEnd < '2012-05-30'
より大きな日付に変更することで、カレンダーを拡張できます。Option(Maxrecursion 0);
シフトが50を超える場合は、クエリの最後に追加してSQLServerの上限を引き上げることをお勧めします。