Chris Crowe's Blog
Ramblings of an IIS MVP ( MVP Since 1997 )

Powered By IIS 7

Search my blog

Some of my readers



My Microsoft Certifications


Dec 15, 1998

Dec 20, 2000

Jan 31, 2001

Jul 22, 2002

Nov 1, 2004

My Microsoft MVP Awards




1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
mvp.support.microsoft.com

 

One of the features of MS Access is the TRANSFORM statement, used to create cross-tabs/pivot tables. It does all of the work of dynamically generating the cross-tabulation and the summary calculations.

T-SQL unfortunately doesn't have this statement, so you're stuck using complicated SQL commands, expensive 3rd party products, or exotic OLAP to make pivot tables...or you can use the following procedure to dynamically create them!

This example would be executed on the Northwind sample database.

SQL Code

EXECUTE crosstab 'SELECT LastName FROM Employees INNER JOIN Orders ON (Employees.EmployeeID=Orders.EmployeeID) GROUP BY LastName', 'count(lastname)', 'Year(OrderDate)', 'Orders'

Results

LastName 1996 1997 1998
Buchanan 11 18 13
Leverling 18 71 38
Fuller 16 41 39
Peacock 31 81 44
Callahan 19 54 31
Suyama 15 33 19
King 11 36 25
Dodsworth 5 19 19
Davolio 26 55 42


For more details see the following article:
http://www.sqlteam.com/item.asp?ItemID=2955

I adjusted the Stored Procedure so that it could handle data with single quotes for field names.

CREATE PROCEDURE crosstab
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)
AS

DECLARE @sql varchar(8000), @delimStart varchar(1), @delimEnd varchar(1), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

select @delimStart = '['
select @delimEnd = ']'

EXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')

SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '[' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'

SELECT @sql=@sql + @DelimStart + convert(varchar(100), pivot) + @DelimEnd + ' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivot

DROP TABLE ##pivot

SELECT @sql=left(@sql, len(@sql)-1)

SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')
print @select
EXEC (@select)
SET ANSI_WARNINGS ON 

 

posted on Monday, September 05, 2005 6:52 PM | Filed Under [ SQL Server ]

Comments


# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
this is realy an appreciated task that has been posted, i realy apprecaite it..


regards

Akbar khan Aryobee
database Technication
UNDP/AIMS
Posted by akbar khan aryobee on 4/18/2007 4:45 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
hi,

thanks u hv done good work.

please help me.

I have one query. my table sturcture and data as follows.

QuestionID Answer
1 abc1
2 A
3 123

i want result in follwing format :

1 2 3 -QuestionId become Columns
abc1 A 123 -Asnwer become Data


Thanks
Manoj Mevada



Posted by Manoj Mevada on 6/22/2007 7:04 AM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
Hi,
I am trying to use above proc in my db , it says Incorrect syntax near Pivot,
Is the statement convert(varchar(100), pivot) rightt? or it should be @pivot ?
Posted by Sripad on 11/2/2007 8:15 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
Hi,
(it says Incorrect syntax near Pivot). Are you using SQL Server 2005 ?
Try to use for example xPivot or iPivot. Pivot is a function in SQL Server 2005
Posted by Andreas Burgardt on 4/9/2008 10:03 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
Msg 156, Level 15, State 1, Procedure crosstab, Line 27
Incorrect syntax near the keyword 'pivot'.
Posted by Bill on 4/16/2008 4:24 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables

Gravatar
because pivot is a keyword in SQL Server, so replace pivot to pivot1
Ex
convert(nvarchar(100), pivot) => convert(nvarchar(100),pivot1)

==> Command(s) completed successfully.

Good luck
Posted by Bill on 4/16/2008 4:57 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables


while using pivot i'm getting error incorrect syntax newar pivot
Posted by ashwini on 6/19/2008 10:00 PM

# re: SQL - Creating Dynamic Cross-Tabs/Pivot Tables


pivot ===> [pivot]
Posted by JL on 4/22/2009 11:21 PM

Post Comment


Title *
Name *
Email
Url
Comment *  
Please add 4 and 3 and type the answer here: