Microsoft SQL Server 2008
Advanced SQL
Best Practices

How to calculate running total fast?

 

Execute the following script in Query Editor calculate running total without using a loop. In the update statement double assignment is applied.

USE tempdb;

 

SELECT * INTO POH from AdventureWorks2008.Purchasing.PurchaseOrderHeader

ORDER by PurchaseOrderID

 

-- select * from POH

 

ALTER TABLE POH ADD RunningTotal money

GO

 

SET NOCOUNT ON

GO

 

DECLARE @RunningTotal MONEY

 

SET @RunningTotal=0

 

UPDATE POH

 

SET @RunningTotal = RunningTotal = @RunningTotal+ISNULL(TotalDue, 0)

GO

 

SELECT * FROM POH

GO

 

 

 

The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page