Search

Showing posts with label Generate running total. Show all posts
Showing posts with label Generate running total. Show all posts

Friday, March 9, 2012

Generate running total

Use below query to generate running total:


Method 1

/*
 SQL Server Running Total Calculation
*/
DECLARE @DateStart date='2004-01-01'
;WITH CTE
     AS (SELECT ID = ROW_NUMBER() OVER(ORDER BY PurchaseOrderID),
                PurchaseOrderID, OrderDate = CONVERT(DATE,OrderDate),SubTotal
         FROM   AdventureWorks2008.Purchasing.PurchaseOrderHeader
         WHERE  OrderDate >= @DateStart)
SELECT   PurchaseOrderID,  OrderDate, SubTotal,
         RunningTotal = (SELECT SUM(SubTotal)
                         FROM   CTE
                         WHERE  ID <= A.ID)
FROM     CTE AS A
ORDER BY ID


Method 2

DECLARE @SalesTbl TABLE (DayCount smallint, Sales money, RunningTotal money)

DECLARE @RunningTotal money

SET @RunningTotal = 0

INSERT INTO @SalesTbl 
SELECT DayCount, Sales, null
FROM Sales
ORDER BY DayCount

UPDATE @SalesTbl
SET @RunningTotal = RunningTotal = @RunningTotal + Sales
FROM @SalesTbl

SELECT * FROM @SalesTbl