Condense Time Periods with SQL

前端 未结 4 1556
春和景丽
春和景丽 2021-02-20 17:41

I have a large data set which for the purpose of this question has 3 fields:

  • Group Identifier
  • From Date
  • To Date

On any given row t

4条回答
  •  悲&欢浪女
    2021-02-20 18:31

    ; with 
    cte as
    (
        select  *, rn = row_number() over (partition by [Group ID] order by [From Date])
        from    tbl
    ),
    rcte as
    (
        select  rn, [Group ID], [From Date], [To Date], GrpNo = 1, GrpFrom = [From Date], GrpTo = [To Date]
        from    cte
        where   rn  = 1
    
        union all
    
        select  c.rn, c.[Group ID], c.[From Date], c.[To Date], 
            GrpNo = case    when    c.[From Date] between r.GrpFrom and dateadd(day, 1, r.GrpTo)
                    or  c.[To Date]   between r.GrpFrom and r.GrpTo
                    then    r.GrpNo
                    else    r.GrpNo + 1
                    end,
            GrpFrom= case   when    c.[From Date] between r.GrpFrom and dateadd(day, 1, r.GrpTo)
                    or  c.[To Date]   between r.GrpFrom and r.GrpTo
                    then    case when c.[From Date] > r.GrpFrom then c.[From Date] else r.GrpFrom end
                    else    c.[From Date] 
                    end,
            GrpTo  = case   when    c.[From Date] between r.GrpFrom and dateadd(day, 1, r.GrpTo)
                    or  c.[To Date]   between r.GrpFrom and dateadd(day, 1, r.GrpTo)
                    then    case when c.[To Date] > r.GrpTo then c.[To Date] else r.GrpTo end
                    else    c.[To Date]  
                    end
    
        from    rcte r
            inner join cte c    on  r.[Group ID]    = c.[Group ID]
                        and r.rn        = c.rn - 1
    )
    select  [Group ID], min(GrpFrom), max(GrpTo)
    from    rcte
    group by [Group ID], GrpNo
    

提交回复
热议问题