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
6 comments:
Cool. So, the variables are set before the row fields are updated?
Simply brilliant. I didn't think that a UPDATE ... SET would use variables that way, but WHY NOT?
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/
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.
Thanks guys. The post has been updated with the link!
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.
Post a Comment