Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get running sum of a column in sql server

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

like image 724
user1448783 Avatar asked Feb 19 '13 08:02

user1448783


People also ask

How do I get the sum of a column in SQL Server?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do you get a running sum in SQL?

In this SQL Server example, we'll use the SUM Function and OVER to find the Running Total. Select in SQL Server Management Studio: Example 3: In this SQL Server example, we will use PARTITION BY with OVER to find the Running Total.

How do you calculate running sum?

Explanation: the simple formula =C2+B3 changes to =C3+B4, =C4+B5, etc. Each time the new value is added to the previous running total. 11.

How do I sum a column in a query?

You can sum a column of numbers in a query by using a type of function called an aggregate function. Aggregate functions perform a calculation on a column of data and return a single value. Access provides a variety of aggregate functions, including Sum, Count, Avg (for computing averages), Min and Max.


2 Answers

if you RDBMS supports window function,

for SQL Server 2012

SELECT  Qty,
        SUM(Qty) OVER (ORDER BY Qty) AS CumulativeTOTAL
FROM    tableName
  • SQLFiddle Demo

for SQL Server 2008

SELECT a.Qty, (SELECT SUM(b.Qty)
               FROM   TableName b
               WHERE  b.Qty <= a.Qty)
FROM   TableName a
ORDER  BY a.Qty;
  • SQLFiddle Demo
like image 136
John Woo Avatar answered Sep 24 '22 18:09

John Woo


SQLFiddle demo

SELECT Qty,
SUM(Qty) OVER (ORDER BY Qty) Run_Sum
FROM t ORDER BY Qty

For SQLServer prior to 2012:

select Qty,
(select sum(Qty) from t where Qty<=t1.Qty)
from t t1 order by Qty

SQLFiddle demo

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 demo

like image 32
valex Avatar answered Sep 23 '22 18:09

valex