Count consecutive duplicate values in SQL

前端 未结 2 546
生来不讨喜
生来不讨喜 2020-12-09 23:19

I have a table like so

ID     OrdID     Value
1      1          0     
2      2          0
3      1          1
4      2          1
5      1          1
6              


        
2条回答
  •  佛祖请我去吃肉
    2020-12-09 23:34

    I am going to presume that id is unique and increasing. You can get counts of consecutive values by using the different of row numbers. The following counts all sequences:

    select grp, value, min(id), max(id), count(*) as cnt
    from (select t.*,
                 (row_number() over (order by id) - row_number() over (partition by value order by id)
                 ) as grp
          from table t
         ) t
    group by grp, value;
    

    If you want the longest sequence of 0s:

    select top 1 grp, value, min(id), max(id), count(*) as cnt
    from (select t.*,
                 (row_number() over (order by id) - row_number() over (partition by value order by id)
                 ) as grp
          from table t
         ) t
    group by grp, value
    having value = 0
    order by count(*) desc
    

提交回复
热议问题