顺序组在sql server中

时间:2013-10-18 21:24:27

标签: sql sql-server select group-by gaps-and-islands

对于此表:

+----+--------+-------+
| 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 |
+----+--------+-------+

我需要对具有相同Status的连续组进行求和以产生此结果。

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

如何在SQL Server中执行此操作?

注意:ID列中的值是连续的。

1 个答案:

答案 0 :(得分:4)

根据我在问题中添加的标签,这是一个空白和岛屿问题。

表现最佳的解决方案可能是

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)

如果ID值不能保证连续,那么您需要使用

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

取而代之的是CTE定义。

SQL Fiddle