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 calculate 12-month moving total?

Execute the following Microsoft SQL Server 2008 T-SQL database script in Query Editor to demonstrate the use of the T-SQL CTE for moving total calculation.

USE AdventureWorks2008;

-- SQL Server 2008 T-SQL code - CTE: Common Table Expression - nested CTE

-- SQL 12-Month Moving Total - Moving 12-Month Total Calculation

WITH CTE

     AS (SELECT   [Month] = CONVERT(DATE,CONVERT(VARCHAR,YEAR(OrderDate)) +

                      '/' + CONVERT(VARCHAR,MONTH(OrderDate)) + '/01'),

                  TotMoSales = SUM(TotalDue)

         FROM     Sales.SalesOrderHeader

         GROUP BY CONVERT(DATE,CONVERT(VARCHAR,YEAR(OrderDate)) + '/' +

                  CONVERT(VARCHAR,MONTH(OrderDate)) + '/01')),

     CTE1

     AS (SELECT   B.*,

                  Moving12MonthTot = SUM(A.TotMoSales)

         FROM     CTE A

                  JOIN CTE B

                    ON A.[Month] BETWEEN DATEADD(mm,-12,b.[Month])

                    AND b.[Month]

         GROUP BY b.[Month],

                  b.TotMoSales)

SELECT   *

FROM     CTE1

ORDER BY [Month]

/*

Month       TotMoSales        Moving12MonthTot

2001-07-01  1172359.4289      1172359.4289

2001-08-01  2605514.9809      3777874.4098

2001-09-01  2073058.5385      5850932.9483

2001-10-01  1688963.2744      7539896.2227

2001-11-01  3690018.6652      11229914.8879

2001-12-01  3097637.3384      14327552.2263

2002-01-01  1605782.1915      15933334.4178

2002-02-01  3130823.0378      19064157.4556

2002-03-01  2643081.0798      21707238.5354

2002-04-01  1905833.9088      23613072.4442

2002-05-01  3758329.2949      27371401.7391

2002-06-01  2546121.9618      29917523.7009

2002-07-01  3781879.0708      33699402.7717

.......

*/

------------

 

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.