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)
 Rows to Columns

Author  Topic 

meeram
Starting Member

2 Posts

Posted - 2011-09-24 : 04:08:39
Hi

I am having the table like below

ServiceID ServiceName HeaderName Value
1 Service1 Test 10
1 Service1 Team 20
1 Service1 Header 30
1 Service1 xxxx 40
1 Service1 yyyy 50

and I want the result like below

ServiceID ServiceName Test Team Header Xxxx Yyyy
1 Service1 10 20 30 40 50

Please help me to achieve this.

Thanks,
Ramasamy

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-24 : 04:28:52
[code]
SELECT ServiceID,ServiceName,
MAX(CASE WHEN HeaderName = 'Test' THEN Value ELSE NULL END) AS Test,
MAX(CASE WHEN HeaderName = 'Team' THEN Value ELSE NULL END) AS Team,
MAX(CASE WHEN HeaderName = 'Header' THEN Value ELSE NULL END) AS Header,
MAX(CASE WHEN HeaderName = 'Xxxx' THEN Value ELSE NULL END) AS Xxxx,
MAX(CASE WHEN HeaderName = 'Yyyy' THEN Value ELSE NULL END) AS Yyyy
FROM table
GROUP BY ServiceID,ServiceName
[/code]

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

Go to Top of Page

meeram
Starting Member

2 Posts

Posted - 2011-09-24 : 04:35:02
Hi,

My Header column value is not fixed, so need to create columns dynamically based on the rows. "CASE" we can use only for the fixed values.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-24 : 04:54:19
ok. then you need to use CASE in dynamic sql. see

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
   

- Advertisement -