How to get count of consecutive dates

前端 未结 3 1345
眼角桃花
眼角桃花 2021-01-04 14:35

For example there is some table with dates:

2015-01-01
2015-01-02
2015-01-03
2015-01-06
2015-01-07
2015-01-11

I have to write ms sql query,

3条回答
  •  感情败类
    2021-01-04 15:00

    You can use this CTE:

    ;WITH CTE AS (
       SELECT [Date],        
              ROW_NUMBER() OVER(ORDER BY [Date]) AS rn,
              CASE WHEN DATEDIFF(Day, PrevDate, [Date]) IS NULL THEN 0
                   WHEN DATEDIFF(Day, PrevDate, [Date]) > 1 THEN 0
                   ELSE 1
              END AS flag
       FROM (
          SELECT [Date], LAG([Date]) OVER (ORDER BY [Date]) AS PrevDate
          FROM #Dates ) d
    )
    

    to produce the following result:

    Date        rn  flag
    ===================
    2015-01-01  1   0
    2015-01-02  2   1
    2015-01-03  3   1
    2015-01-06  4   0
    2015-01-07  5   1
    2015-01-11  6   0
    

    All you have to do now is to calculate a running total of flag up to the first occurrence of a preceding zero value:

    ;WITH CTE AS (
       ... cte statements here ...
    )
    SELECT [Date], b.cnt + 1
    FROM CTE AS c
    OUTER APPLY (
       SELECT TOP 1 COALESCE(rn, 1) AS rn 
       FROM CTE
       WHERE flag = 0 AND rn < c.rn
       ORDER BY rn DESC
    ) a 
    CROSS APPLY (
       SELECT COUNT(*) AS cnt
       FROM CTE 
       WHERE c.flag <> 0 AND rn < c.rn AND rn >= a.rn
    ) b
    

    OUTER APPLY calculates the rn value of the first zero-valued flag that comes before the current row. CROSS APPLY calculates the number of records preceding the current record up to the first occurrence of a preceding zero valued flag.

提交回复
热议问题