Getting Started with ASP.NET MVC - Part 6: ASP.NET MVC and Entity Framework
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.


Upload Image Close it
Select File

Browse by Tags · View All
sql_server 217
t-sql 211
tsql 113
sqlserver 94
BRH 78
#SQLServer 65
#TSQL 55
SQL Server 32
function 11
SSMS 9

Archive · View All
August 2007 17
August 2010 8
June 2011 7
November 2007 7
November 2011 6
August 2011 6
October 2011 6
July 2011 6
September 2011 6
December 2011 6

Madhivanan's TSQL Blog

Dynamic PIVOT in SQL Server 2005

Aug 27 2008 1:37PM by Madhivanan   

The PIVOT operator available in SQL Server 2005 is used to generate the Cross-tab results

Consider this example 
select * from 
(
    select Year(OrderDate) as pivot_col,e.lastname, o.OrderDate FROM northwind..Employees as e
    INNER JOIN northwind..Orders as o ON (e.EmployeeID=o.EmployeeID) 
) as t 
pivot 
(
    Count(OrderDate) for pivot_col in ([1996],[1997])
) as p
which shows total orders of each employees for years 1996 and 1997 

What if we want to have this for all the years available in the table
You need to use dynamic sql


This procedure is used to generate Dynamic Pivot results

The approach is very similar to my Dynamic Crosstab with multiple PIVOT Columns blog post 
which can be used in SQL Server 2000
create procedure dynamic_pivot
(
@select varchar(2000),
@PivotCol varchar(100), 
@Summaries varchar(100)
) as 
declare @pivot varchar(max), @sql varchar(max)
select @select =replace(@select,'select ','select '+@PivotCol+' as pivot_col,')
 

create table #pivot_columns (pivot_column varchar(100))

Select @sql='select distinct pivot_col from ('+@select+') as t'

insert into #pivot_columns
exec(@sql)

select @pivot=coalesce(@pivot+',','')+'['+pivot_column+']'from #pivot_columns

select @sql=
'
    select * from 
    (
        '+@select+'
    ) as t 
    pivot 
    (
        '+@Summaries+' for pivot_col in ('+@pivot+')
    ) as p
' 

exec(@sql) 

Purpose : Find total sales made by each employee for each year(from Employees and Orders table from Northwind databases)

Usage :

EXEC dynamic_pivot
'SELECT e.lastname, o.OrderDate FROM northwind..Employees as e
INNER JOIN northwind..Orders as o ON (e.EmployeeID=o.EmployeeID) ',
'Year(OrderDate)',
'Count(OrderDate)'

Purpose : Find total sales made by each company for each product(from products, order details and suppliers table from Northwind database)

Usage :

EXEC dynamic_pivot
'SELECT s.companyname,coalesce(od.unitprice*od.quantity ,0) as total_cost FROM northwind..products as p
inner join northwind..[order details] as od on p.productid=od.productid
inner join northwind..suppliers as s on p.supplierid=s.supplierid',
'productname',
'sum(total_cost)'

Tags: t-sql, sql_server, dynamic_cross_tab, dynamic_pivot, cross_tab, pivot,


Madhivanan
4 · 39% · 8850
3
 
0
Lifesaver
 
0
Refreshed
 
0
Learned
 
0
Incorrect



Submit

3  Comments  

  • Madhivanan, lots of nice reference material! I very often often google for "Madhivanan+dynamic pivoting" and copy the code from here.

    I noticed that you don't have a "drop table #pivot_columns" in the code. May not matter because the SQL OS should take care of it.

    commented on Apr 14 2011 10:01PM  .  Report Abuse This post is not formatted correctly
    SunitaBeck
    940 · 0% · 16
  • Sunita, Thanks for the feedback. As the temporary table is created inside a procedure, it will be dropped automatically after the procedure is executed

    commented on Apr 15 2011 2:56AM  .  Report Abuse This post is not formatted correctly
    Madhivanan
    4 · 39% · 8850
  • yes, and you should always clean up after yourself regardless

    commented on Mar 26 2012 12:54PM  .  Report Abuse This post is not formatted correctly
    Brett
    2307 · 0% · 2

Your Comment


Sign Up or Login to post a comment.

"Dynamic PIVOT in SQL Server 2005" rated 5 out of 5 by 3 readers
Dynamic PIVOT in SQL Server 2005 , 5.0 out of 5 based on 3 ratings
    Copyright © Beyondrelational.com Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising