如何获得累计金额 [英] How to get cumulative sum

查看:23
本文介绍了如何获得累计金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

declare  @t table
    (
        id int,
        SomeNumt 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

上面的选择返回给我以下内容.

the above select returns me the following.

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

推荐答案

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

SQL Fiddle 示例

输出

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

这是一个适用于大多数数据库平台的通用解决方案.如果您的特定平台(例如 gareth's)有更好的解决方案可用,请使用它!

this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!

这篇关于如何获得累计金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆