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, but can start with any value. I need a query that will return a count of consecutive rows with the same ID and Value.
For example, let's say I have the following data:
ID  Sequence  Value
--  --------  -----
1         1      1
5         1    100
5         2    200
5         3    200
5         4    100
10       10     10
I want the following result:
ID  Start  Value  Count
--  -----  -----  -----
1      1      1      1
5      1    100      1
5      2    200      2
5      4    100      1
10    10     10      1
I tried
SELECT ID, MIN([Sequence]) AS Start, Value, COUNT(*) AS [Count]
 FROM DATA
 GROUP BY ID, Value
 ORDER BY ID, Start
but that gives
ID  Start  Value  Count
--  -----  -----  -----
1      1      1      1
5      1    100      2
5      2    200      2
10    10     10      1
which groups all rows with the same values, not just consecutive rows.
Any ideas? From what I've seen, I believe I have to left join the table with itself on consecutive rows using ROW_NUMBER(), but I am not sure exactly how to get counts from that.
Thanks in advance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With