Search

Saturday, January 8, 2011

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, 0INSERT INTO #TmpTable SELECT 2, 14, 65, 0, 0INSERT INTO #TmpTable SELECT 3, 34, 22, 0, 0INSERT INTO #TmpTable SELECT 4, 56, 22, 0, 0INSERT INTO #TmpTable SELECT 5, 7, 23, 0, 0
QUERY (results not guaranteed)
DECLARE @rowtot intDECLARE @runtot intSET @rowtot = 0 -- set rowtotal to 0SET @runtot = 0 -- set runningtotal to 0UPDATE #TmpTableSET RowTotal = @rowtot,RunningTotal = @runtot,@rowtot = COALESCE(Col1, 0) + COALESCE(Col2, 0),@runtot = @runtot + @rowtotSELECT * 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.

No comments:

Post a Comment