SQLUSA
BI TRIO 2008
FREE TRIAL
CLICK HERE TO ORDER

SQL Server 2008 Best Practices
SQL Server 2005 Best Practices

How to generate running totals with a simple update?

Execute the following SQL Server T-SQL script in SSMS Query Editor to demonstrate running total generation on the Total Due amount using multiple-value assignment in UPDATE. There is an ongoing debate in database circles about the validity of such use.

USE AdventureWorks;

-- SQL running total - SQL multiple value assignment update

DECLARE  @RunningTotal MONEY

DECLARE  @Result  TABLE(

                        SalesOrderID INT    NOT NULL    PRIMARY KEY,

                        TotalDue     MONEY,

                        RunningTotal MONEY

                        )

 

SET @RunningTotal = 0.0

 

INSERT INTO @Result

           (SalesOrderID,

            TotalDue)

SELECT   SalesOrderID,

         TotalDue

FROM     Sales.SalesOrderHeader

ORDER BY SalesOrderID

 

UPDATE @Result

SET    @RunningTotal = RunningTotal = @RunningTotal + TotalDue

-- SQL currency formatting

SELECT   SalesOrderId,

         [Total Due] = '$' + convert(VARCHAR,TotalDue,1),

         [Running Total] = '$' + convert(VARCHAR,RunningTotal,1)

FROM     @Result

ORDER BY SalesOrderID

 

GO

/*

Partial results

 

SalesOrderId      Total Due   Running Total

43659             $23,153.23  $23,153.23

43660             $1,457.33   $24,610.56

43661             $36,865.80  $61,476.36

43662             $32,474.93  $93,951.30

43663             $472.31     $94,423.61

43664             $27,510.41  $121,934.02

43665             $16,158.70  $138,092.71

*/

 

 

The World Leader in SQL Server 2008 Training
The future is just a CLICK away. Your future!
 
SQLUSA.com Home Page

Copyright 2005-2010, SMI Corp. All Rights Reserved.

SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.