October 21, 2010

Calculate Running Total and Row Total in SQL Server




Let us see how to calculate Row Totals and Running Totals in SQL Server. In the code shown below, we will first calculate the sum of Col1 and Col2 for each row and then also maintain a Running Total of the same.

Update: As williamdurkin and TheSQLGuru pointed out, the method in the T-SQL query below does not guarantee the order that the update runs in.

The correct solution is given by Jeff Moden over here http://www.sqlservercentral.com/articles/Advanced+Querying/61716/ (Requires Registration to view) . Thanks guys for the correction!

SAMPLE CODE

CREATE TABLE #TmpTable
(
ID int, Col1 int, Col2 int,
RowTotal int, RunningTotal int
)

INSERT INTO #TmpTable SELECT 1, 5, 2, 0, 0
INSERT INTO #TmpTable SELECT 2, 14, 65, 0, 0
INSERT INTO #TmpTable SELECT 3, 34, 22, 0, 0
INSERT INTO #TmpTable SELECT 4, 56, 22, 0, 0
INSERT INTO #TmpTable SELECT 5, 7, 23, 0, 0

QUERY (results not guaranteed)

DECLARE @rowtot int
DECLARE @runtot int
SET @rowtot = 0 -- set rowtotal to 0
SET @runtot = 0 -- set runningtotal to 0

UPDATE #TmpTable
SET RowTotal = @rowtot,
RunningTotal = @runtot,
@rowtot = COALESCE(Col1, 0) + COALESCE(Col2, 0),
@runtot = @runtot + @rowtot

SELECT * FROM #TmpTable

The code is quite easy to understand. We are maintaining two variables @rowtot (for RowTotal) and @runtot (Running Total) and use the Update Table command to update the Row Total and Running Total for each row.

OUTPUT

image


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

6 Responses to "Calculate Running Total and Row Total in SQL Server"
  1. Anonymous said...
    October 21, 2010 at 7:28 AM

    Cool. So, the variables are set before the row fields are updated?

  2. Anonymous said...
    October 22, 2010 at 8:58 AM

    Simply brilliant. I didn't think that a UPDATE ... SET would use variables that way, but WHY NOT?

  3. williamdurkin said...
    October 23, 2010 at 4:24 AM

    This method doesn't guarantee the order that the update runs in, so should not be done IMO.

    The data that is returned while you do the update is arbitrary, even if there is a clustered index on the table.

    For more info, check out the article by Jeff Moden on SqlServerCentral.com
    http://www.sqlservercentral.com/articles/Advanced+Querying/61716/

  4. TheSQLGuru said...
    October 23, 2010 at 6:33 AM

    THIS METHOD IS NOT GUARANTEED TO GIVE YOU THE CORRECT ANSWER, AND IS NOT SUPPORTED BY MICROSOFT AS A VALID PROGRAMMING METHOD!!!!

    Having said that, if you read and STRICTLY ADHERE to the guidance put forth by Jeff Moden in the referenced link above there is a low (but non-zero) probability that you will get incorrect results.

  5. Suprotim Agarwal said...
    October 24, 2010 at 7:39 PM

    Thanks guys. The post has been updated with the link!

  6. darlove said...
    November 4, 2010 at 10:09 AM

    Isn't it better to just use the very helpful window function row_number()??? Once you number the rows in the correct order, you can simply create a running total by a simple subquery... or even a join with order guaranteed. Just a suggestion.

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions