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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 pivot ?

Author  Topic 

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2011-09-15 : 08:13:10
The stored procedure (sp) returns fields as follows:

YearQuarter Field1 Field2 Field3 Field4
null 5.33 5.6 4.2 5
2010 -1.43 -3.5 2.54 3.1
Q2 2010 2.5 4.3 2.2 8.1
Q1 2011 -2.4 9.4 4.3 1.2

How can I show this as follows please?

null 2010 Q2 2010 Q1 2011

Field1 5.33 -1.43 2.5 -2.4
Field2 5.6 -3.5 4.3 9.4
Field3 4.2 2.54 2.2 4.3
Field4 5 3.1 8.1 1.2

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-15 : 11:33:07
[code]
SELECT Field,[Null],[2010],[Q2 2010],[Q1 2011]
FROM
(
SELECT ISNULL(YearQuarter,'Null') AS YearQuarter,Field,Val
FROM table
UNPIVOT ( Val FOR Field IN ([Field1],[Field2],[Field3],[Field4]))u
)m
PIVOT (MAX(Val) FOR YearQuarter IN ([Null],[2010],[Q2 2010],[Q1 2011]))p
[/code]

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

Go to Top of Page

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2011-09-15 : 11:49:23
The fields in YearQuarter in () are dynamic and can change depending on parameters, etc.
Can it be dynamic?
Thanks
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-15 : 12:56:38
yep. it can. for that you need to use dynamic sql like below

http://sqlblogcasts.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

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

Go to Top of Page

arkiboys
Master Smack Fu Yak Hacker

1433 Posts

Posted - 2011-09-16 : 03:57:36
Thank you
Go to Top of Page
   

- Advertisement -