SQL中的累积和 [英] Cumulative sum in SQL

查看:76
本文介绍了SQL中的累积和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现此输出,我有一个像ID,Date,Qty但我想要累积数量的列。



How to achieve this output, I have a columns like ID,Date,Qty but i want cumulative qty.

ID           Date       Qty       Cummulative
1          2011-02-23   100        100
1          2011-03-18   300        400
1          2013-04-23   100        500
2          2010-01-20    50         50
2          2013-03-23   100        150





如何实现这一目标,我在谷歌搜索这个但是这不满足我的要求..



任何人都可以帮助我...



How to achieve this , i'm searching in google for this but that's not satisfied my requirement..

can anybody help me out of this...

推荐答案

嗨Naveen,



请看一下这个例子。



它可能对你有帮助。



Hi Naveen ,

Please look into the example.

It may be help you .

Create table #tt1 (sno int identity,Amt int)

insert into #tt1 values (100)
insert into #tt1 values (200)
insert into #tt1 values (300)
insert into #tt1 values (400)

select * from #tt1

select a.sno,a.Amt,Sum(b.Amt) as Cum_Amt from #tt1 a cross join #tt1 b
where a.sno>=b.sno group by a.sno,a.Amt
order by a.sno,a.Amt


试试这个 - >



Try this->

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


SELECT      T1.SL,
            T1.GroupName,
            T1.Amount,
            SUM(T2.Amount) as CumulativeSum
FROM  @Temp T1 INNER JOIN
            @Temp T2 on T1.SL >= T2.SL
GROUP BY T1.SL,T1.GroupName, T1.Amount
ORDER BY T1.SL





详情请见:



http://cybarlab.blogspot。合作m / 2013/06 / cumulative-sum-in-sql.html [ ^ ]


这篇关于SQL中的累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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