5

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

2
  • Thanks, i have the same problem. Commented Oct 16, 2017 at 2:58
  • I hope you saw the answer below! Commented Oct 16, 2017 at 3:10

2 Answers 2

4

try SUM() OVER

SELECT  
      item, 
      week, 
      amount,
      SUM(amount) over (partition by item order by Week) as Total
FROM yourTable
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome.. thank you so much. Only thing I had to do was SUM(Amount) over (partition by item order by Week) as Total
2

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/

1 Comment

This code works just fine thanks.. but there seems to be a performance degradation when I use the Rows Unbounded Preceding. My query that runs in about 4 seconds is dragged out to 25 seconds.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.