SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

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

*/

 

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


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

SQL Server 2012 is a program product of Microsoft Corporation.
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.