Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL Pivot on more than one column?

Author  Topic 

rogerclerkwell
Yak Posting Veteran

85 Posts

Posted - 2011-12-09 : 04:41:06
I need to pivot on more than one column but been trying for hours and can't make it happen! Is it possible?




my script which works on one column:

DECLARE @query VARCHAR(4000)
DECLARE @prodtype VARCHAR(2000)
SELECT @prodtype = STUFF(( SELECT DISTINCT
'],[' + ltrim(([Product Type]))
FROM ProductCosts
ORDER BY '],[' + ltrim(([Product Type]))
FOR XML PATH('')
), 1, 2, '') + ']'

SET @query =

'SELECT * FROM
(
SELECT [ProductID], [Product Type], [Product Value]
FROM ProductCosts
)t

PIVOT (SUM([Product Value]) FOR [Product Type]
IN ('+@prodtype+')) AS pvt1
'

EXECUTE (@query)

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-09 : 04:44:17
for multi column pivot use this

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

rogerclerkwell
Yak Posting Veteran

85 Posts

Posted - 2011-12-09 : 04:54:22
Thank you visakh16 I'll take a look.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-09 : 05:05:36
wc

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -