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 architect dynamic PIVOT?

Execute the following Microsoft SQL Server T-SQL sample script in SSMS Query Editor to demonstrate the design of a dynamic PIVOT for crosstab (matrix) report generation:

-- MSSQL pivot crosstab report - SQL dynamic pivot - SQL dynamic sql

-- SQL dynamic crosstab report with pivot

USE AdventureWorks

GO

 

DECLARE  @OrderYear  AS  TABLE(

                               YYYY INT    NOT NULL    PRIMARY KEY

                               )

DECLARE  @DynamicSQL  AS NVARCHAR(4000)

INSERT INTO @OrderYear

SELECT DISTINCT YEAR(OrderDate)

FROM   Sales.SalesOrderHeader

 

DECLARE  @ReportColumnNames  AS NVARCHAR(MAX),

         @IterationYear      AS INT

SET @IterationYear = (SELECT MIN(YYYY)

                      FROM   @OrderYear)

SET @ReportColumnNames = N''

 

-- Assemble pivot list dynamically

WHILE (@IterationYear IS NOT NULL)

  BEGIN

    SET @ReportColumnNames = @ReportColumnNames + N',' +
      QUOTENAME
(CAST(@IterationYear AS NVARCHAR(10)))

    SET @IterationYear = (SELECT MIN(YYYY)

                          FROM   @OrderYear

                          WHERE  YYYY > @IterationYear)

  END

SET @ReportColumnNames = SUBSTRING(@ReportColumnNames,2,LEN(@ReportColumnNames))

PRINT @ReportColumnNames

-- [2001],[2002],[2003],[2004]

SET @DynamicSQL = N'SELECT * FROM (SELECT [Store (Freight Summary)]=s.Name, 

  YEAR(OrderDate) AS OrderYear,  Freight = convert(money,convert(varchar, Freight)) 

  FROM Sales.SalesOrderHeader soh  JOIN Sales.Store s 

  ON soh.CustomerID = s.CustomerID) as Header 

  PIVOT (SUM(Freight)

  FOR OrderYear IN(' + @ReportColumnNames + N'))  AS Pvt ORDER BY 1'

 

PRINT @DynamicSQL -- Testing & debugging

 

/*

SELECT * FROM (SELECT [Store (Freight Summary)]=s.Name, 

YEAR(OrderDate) AS OrderYear,  Freight = convert(money,convert(varchar, Freight)) 

FROM Sales.SalesOrderHeader soh  JOIN Sales.Store s 

ON soh.CustomerID = s.CustomerID) as Header 

PIVOT (SUM(Freight) FOR OrderYear IN([2001],[2002],[2003],[2004])) 

AS Pvt ORDER BY 1

*/

 

-- Execute dynamic sql

EXEC sp_executesql @DynamicSQL

GO

 

/* Partial results

 

Store (Freight Summary)             2001        2002        2003        2004

Grease and Oil Products Company     104.02      555.02      726.75      272.28

Great Bicycle Supply                4430.26     3871.35     NULL        NULL

Great Bikes                         1653.89     7445.16     7525.98     4584.63

Greater Bike Store                  489.79      1454.78     864.08      245.22

*/

Related link: http://sqlusa.com/bestpractices/dynamicsql/

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.