Harry
Harry

Reputation: 2951

Adding a running total column in SQL Server

I have a result set from a SQL Server query as below:

Item Week Amount

1     1      500
1     2     -100
1     3     -200
2     1      800
2     2     -600
2     3     -800

What I want to know is, is it possible to derive a fourth column that gives a running total of amount for each item?

My desired result is as follows:

Item Week Amount Total

1     1      500  500
1     2     -100  400
1     3     -200  200
2     1      800  800
2     2     -600  200 
2     3     -800 -600

I am using SQL Server 2008

Upvotes: 5

Views: 5540

Answers (2)

Dennis C
Dennis C

Reputation: 24747

You will need a SQL Server 2012 to support ROWS PRECEDING functions.

SELECT  
  item, 
  week, 
  amount,
  SUM(amount) over (partition by item order by Week
       ROWS UNBOUNDED PRECEDING
  ) as Total
FROM yourTable

http://stevestedman.com/2012/03/rows-preceding-and-following-in-tsql-2012/

Upvotes: 2

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48207

try SUM() OVER

SELECT  
      item, 
      week, 
      amount,
      SUM(amount) over (partition by item order by Week) as Total
FROM yourTable

Upvotes: 4

Related Questions