How to get count of consecutive dates

前端 未结 3 1357
眼角桃花
眼角桃花 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 14:54

    I'm assuming this table:

    SELECT * 
    INTO #Dates
    FROM (VALUES
      (CAST('2015-01-01' AS DATE)),
      (CAST('2015-01-02' AS DATE)),
      (CAST('2015-01-03' AS DATE)),
      (CAST('2015-01-06' AS DATE)),
      (CAST('2015-01-07' AS DATE)),
      (CAST('2015-01-11' AS DATE))) dates(d);
    

    Here's a recursive solution with explanations:

    WITH
      dates AS (
        SELECT
          d, 
          -- This checks if the current row is the start of a new group by using LAG()
          -- to see if the previous date is adjacent
          CASE datediff(day, d, LAG(d, 1) OVER(ORDER BY d)) 
            WHEN -1 THEN 0 
            ELSE 1 END new_group,
          -- This will be used for recursion
          row_number() OVER(ORDER BY d) rn
        FROM #Dates
      ),
      -- Here, the recursion happens
      groups AS (
        -- We initiate recursion with rows that start new groups, and calculate "GRP"
        -- numbers
        SELECT d, new_group, rn, row_number() OVER(ORDER BY d) grp
        FROM dates
        WHERE new_group = 1
        UNION ALL
        -- We then recurse by the previously calculated "RN" until we hit the next group
        SELECT dates.d, dates.new_group, dates.rn, groups.grp
        FROM dates JOIN groups ON dates.rn = groups.rn + 1
        WHERE dates.new_group != 1
      )
    -- Finally, we enumerate rows within each group
    SELECT d, row_number() OVER (PARTITION BY grp ORDER BY d)
    FROM groups
    ORDER BY d
    

    SQLFiddle

提交回复
热议问题