Sequential Group By in sql server

巧了我就是萌 提交于 2020-01-11 07:47:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/19459274/sequential-group-by-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!