0

I need to sum the previous rows in sql 2005. This my table

id  date     valuein     valueout    misstotal     
5   2/2/2013    0            500       -500    
2  25/2/2013    0            300       -300
7  25/2/2013    900          0          900
4  25/2/2013   2000          0          2000

misstotal = ( valuein - valueout)

This is not the problem

I want a column to have the total balance like below table in the total column.

id  date     valuein     valueout    misstotal     total
5   2/2/2013    0            500       -500         -500
2  25/2/2013    0            300       -300         -800
7  25/2/2013    900          0          900          100
4  25/2/2013   2000          0          2000         2100

So whats the code for doing this sum?

Ravi Singh
  • 2,042
  • 13
  • 29

1 Answers1

0

This blog post gives you a number of options for calculating a running total in SQL Server 2005:

http://geekswithblogs.net/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx

A good way is to insert you data into a temporary table, then update this table to populate the running total column like so:

SET @RunningTotal = 0 

UPDATE @TmpTable
SET @RunningTotal = total = @RunningTotal + misstotal
FROM @TmpTable

SELECT * FROM @TmpTable
Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158
  • While this may answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Taryn Mar 07 '13 at 12:25