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


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

6 comments:

Anonymous said...

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

Anonymous said...

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

williamdurkin said...

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/

TheSQLGuru said...

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.

Suprotim Agarwal said...

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

darlove said...

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.