Detect consecutive dates ranges using SQL

后端 未结 7 1223
南笙
南笙 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 08:38

    Here you go..

    ;WITH CTEDATES
    AS
    (
        SELECT ROW_NUMBER() OVER (ORDER BY Infodate asc ) AS ROWNUMBER,infodate FROM YourTableName  
    
    ),
     CTEDATES1
    AS
    (
       SELECT ROWNUMBER, infodate, 1 as groupid FROM CTEDATES WHERE ROWNUMBER=1
       UNION ALL
       SELECT a.ROWNUMBER, a.infodate,case datediff(d, b.infodate,a.infodate) when 1 then b.groupid else b.groupid+1 end as gap FROM CTEDATES A INNER JOIN CTEDATES1 B ON A.ROWNUMBER-1 = B.ROWNUMBER
    )
    
    select min(mydate) as startdate, max(infodate) as enddate from CTEDATES1 group by groupid
    

    please don't forget to mark it as answer, if this answers your question.

提交回复
热议问题