Combine consecutive date ranges

前端 未结 4 542
礼貌的吻别
礼貌的吻别 2020-12-06 12:28

Using SQL Server 2008 R2,

I\'m trying to combine date ranges into the maximum date range given that one end date is next to the following start date.

The da

4条回答
  •  一生所求
    2020-12-06 13:14

    A modified script for combining all overlapping periods.
    For example
    01.01.2001-01.01.2010
    05.05.2005-05.05.2015

    will give one period:
    01.01.2001-05.05.2015

    tbl.enddate must be completed

    ;WITH cte
      AS(
    SELECT
      a.employmentid
      ,a.startdate
      ,a.enddate
    from tbl a
    left join tbl c on a.employmentid=c.employmentid
        and a.startdate > c.startdate
        and a.startdate <= dateadd(day, 1, c.enddate)
    WHERE c.employmentid IS NULL
    
    UNION all
    
    SELECT
      a.employmentid
      ,a.startdate
      ,a.enddate
    from cte a
    inner join tbl c on a.startdate=c.startdate
        and (c.startdate = dateadd(day, 1, a.enddate) or (c.enddate > a.enddate and c.startdate <= a.enddate))
    )
    select distinct employmentid,
              startdate,
              nullif(max(enddate),'31.12.2099') enddate
    from cte
    group by employmentid, startdate
    

提交回复
热议问题