SQL: Merge Date Ranges

后端 未结 3 487
星月不相逢
星月不相逢 2020-12-06 02:59

I\'ve a table, which describes work slices of a business working calendar: (date format is 24 hours format)

PK  | STARTDATE          | ENDDATE
______________         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-06 03:14

    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.

提交回复
热议问题