本文介绍了如何在SQL Server中获取列的运行总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我在Bills表中有一列名为Qty的列我想要一列显示这样的Qty列的运行总和:
Hi I have a column with name Qty from table Billsi want a column that show the running sum of Qty column like this :
Qty Run_Sum
1 1
2 3
3 6
4 10
5 15
建议我使用一些合适的方法来运行谢谢"
Suggest me some appropriate method to make running some thankx
推荐答案
SELECT Qty,
SUM(Qty) OVER (ORDER BY Qty) Run_Sum
FROM t ORDER BY Qty
对于2012年之前的SQLServer:
For SQLServer prior to 2012:
select Qty,
(select sum(Qty) from t where Qty<=t1.Qty)
from t t1 order by Qty
或者您也可以不使用子查询来做到这一点:
Or also you can do it without subquery:
select t1.Qty, sum(t2.Qty)
from t t1
join t t2 on (t1.Qty>=t2.Qty)
group by t1.Qty
order by t1.Qty
这篇关于如何在SQL Server中获取列的运行总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!