Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count consecutive duplicate values in SQL

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          0
7      1          0
8      2          0
9      2          1
10     1          0
11     2          0

I want to get the count of consecutive value where the value is 0. Using the example above the result will be 3 (Rows 6, 7 and 8). I am using sql server 2008 r2.

like image 344
abeuwe Avatar asked Dec 02 '14 14:12

abeuwe


People also ask

How do you sum duplicate values in SQL?

You can specify either ALL or DISTINCT modifier in the SUM() function. The DISTINCT modifier instructs the SUM() function to calculate the total of distinct values, which means the duplicates are eliminated. The ALL modifier allows the SUM() function to return the sum of all values including duplicates.

What is Dedup in SQL?

Data deduplication is a process that eliminates excessive copies of data and significantly decreases storage capacity requirements. Deduplication can be run as an inline process as the data is being written into the storage system and/or as a background process to eliminate duplicates after the data is written to disk.


1 Answers

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
like image 76
Gordon Linoff Avatar answered Oct 24 '22 16:10

Gordon Linoff