SQL Server GROUP BY COUNT Consecutive Rows Only

前端 未结 1 1482
说谎
说谎 2021-02-06 09:38

I have a table called DATA on Microsoft SQL Server 2008 R2 with three non-nullable integer fields: ID, Sequence, and Value. Sequence values with the same ID will be consecutive,

相关标签:
1条回答
  • 2021-02-06 10:26

    You can use Sequence - ROW_NUMBER() OVER (ORDER BY ID, Val, Sequence) AS g to create a group:

    SELECT
      ID,
      MIN(Sequence) AS Sequence,
      Val,
      COUNT(*) AS cnt
    FROM
    (
      SELECT
        ID,
        Sequence,
        Sequence - ROW_NUMBER() OVER (ORDER BY ID, Val, Sequence) AS g,
        Val
      FROM
        yourtable
    ) AS s
    GROUP BY
      ID, Val, g
    

    Please see a fiddle here.

    0 讨论(0)
提交回复
热议问题