Detect consecutive dates ranges using SQL

后端 未结 7 1228
南笙
南笙 2020-11-28 07:54

I want to fill the calendar object which requires start and end date information. I have one column which contains a sequence of dates. Some of the dates are consecutive (ha

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 08:29

    No joins or recursive CTEs needed. The standard gaps-and-island solution is to group by (value minus row_number), since that is invariant within a consecutive sequence. The start and end dates are just the MIN() and MAX() of the group.

    WITH t AS (
      SELECT InfoDate d,ROW_NUMBER() OVER(ORDER BY InfoDate) i
      FROM @d
      GROUP BY InfoDate
    )
    SELECT MIN(d),MAX(d)
    FROM t
    GROUP BY DATEDIFF(day,i,d)
    

提交回复
热议问题