如何在sql server中获取一列的运行总和

2021-12-19 00:00:00 sql select sql-server-2008 sql-server

我在 Bills 表中有一个名为 Qty 的列我想要一个列显示 Qty 列的运行总和,如下所示:

Hi I have a column with name Qty from table Bills i 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

推荐答案

SQLFiddle demo

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

SQLFiddle 演示

或者你也可以不用子查询:

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

SQLFiddle 演示

相关文章