Question

For this Table:

+----+--------+-------+
| ID | Status | Value |
+----+--------+-------+
|  1 |      1 |     4 |
|  2 |      1 |     7 |
|  3 |      1 |     9 |
|  4 |      2 |     1 |
|  5 |      2 |     7 |
|  6 |      1 |     8 |
|  7 |      1 |     9 |
|  8 |      2 |     1 |
|  9 |      0 |     4 |
| 10 |      0 |     3 |
| 11 |      0 |     8 |
| 12 |      1 |     9 |
| 13 |      3 |     1 |
+----+--------+-------+

I need to sum sequential groups with the same Status to produce this result.

+--------+------------+
| Status | Sum(Value) |
+--------+------------+
|      1 |         20 |
|      2 |          8 |
|      1 |         17 |
|      2 |          1 |
|      0 |         15 |
|      1 |          9 |
|      3 |          1 |
+--------+------------+

How can I do that in SQL Server?

NB: The values in the ID column are contiguous.

Was it helpful?

Solution

Per the tag I added to your question this is a gaps and islands problem.

The best performing solution will likely be

WITH T
     AS (SELECT *,
                ID - ROW_NUMBER() OVER (PARTITION BY [STATUS] ORDER BY [ID]) AS Grp
         FROM   YourTable)
SELECT [STATUS],
       SUM([VALUE]) AS [SUM(VALUE)]
FROM   T
GROUP  BY [STATUS],
          Grp
ORDER  BY MIN(ID)

If the ID values were not guaranteed contiguous as stated then you would need to use

ROW_NUMBER() OVER (ORDER BY [ID]) - 
       ROW_NUMBER() OVER (PARTITION BY [STATUS] ORDER BY [ID]) AS Grp

Instead in the CTE definition.

SQL Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top