SQL:将事件拆分为多行

时间:2012-05-30 02:45:26

标签: sql sql-server sql-server-2008

在这里查看我的SQLFiddle(link

在SQL Server 2008中,我有事件开始和结束时间表,如下图所示。

enter image description here

我需要编写一个查询,让我可以弄清楚每个事件中有多少属于哪个工作班次。我们的班次为12小时,时间为06:00-18:00和18:00-06:00。

查询应该产生如下图所示的结果。

enter image description here

然后,我可以计算出特定工作班次的总事件持续时间。

从第一张图片到第二张图片,我该怎么办?

1 个答案:

答案 0 :(得分:7)

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 Fiddle version

在此解决方案中,我生成了每个班次的开始和结束日期的日历。您可以通过将Where ShiftEnd < '2012-05-30'更改为更大的日期来扩展日历。请注意,如果最终轮换次数超过50次,则需要将Option(Maxrecursion 0);添加到查询结尾以提升SQL Server的上限。