如何求累积和？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (22)
```declare  @t table
(
id int,
)

insert into @t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23

select * from @t```

```id  SomeNumt
1   10
2   12
3   3
4   15
5   23```

```id  srome   CumSrome
1   10  10
2   12  22
3   3   25
4   15  40
5   23  63```

2 个回答

```select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
order by t1.id```

```| ID | SOMENUMT | SUM |
-----------------------
|  1 |       10 |  10 |
|  2 |       12 |  22 |
|  3 |        3 |  25 |
|  4 |       15 |  40 |
|  5 |       23 |  63 |```

SQLServer的最新版本允许以下操作。

```SELECT
RowID,
Col1,
SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId```

```SELECT
GroupID,
RowID,
Col1,
SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId```