Microsoft SQL Server 2005 Best Practices

How to generate running totals with a simple update?

 

Execute the following script in Query Editor to demonstrate running total generation on the Total Due amount:

USE AdventureWorks;

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

select SalesOrderId,
[Total Due]='$'+convert(varchar,TotalDue,1),
[Running Total]='$'+convert(varchar,RunningTotal,1)
from @Result
order by SalesOrderID
go




 

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