Hi Team,
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 0
2 1
3 3
4 6
5 10
Please help me to solve this
Hi Team,
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 0
2 1
3 3
4 6
5 10
Please help me to solve this
SELECT
Qty,
SUM(Qty) OVER (ORDER BY Qty) as Run_Sum
FROM
YourTable;
will you have duplicate Qty ?
Yes.We cannot restrict.
Yes khtan.We cannot restrict.
; with cte as
(
select rn = row_number() over (order by Qty), Qty
from yourtable
)
select Qty, Run_Sum = sum(Qty) over (order by rn) - Qty
from cte
Still we are getting the error "Incorrect syntax near 'order'".
What version of SQL Server are you using? The query works only for SQL 2012 or later.
this works for before SQL 2012
; with cte as
(
select rn = row_number() over (order by Qty), Qty
from your_table
)
select Qty, Run_Sum = Run_Sum - Qty
from cte d
cross apply
(
select Run_Sum = sum(Qty)
from cte x
where x.rn <= d.rn
) rs