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 2005 Forums
 Transact-SQL (2005)
 Please help me on data selection

Author  Topic 

pacolim
Starting Member

11 Posts

Posted - 2010-02-03 : 04:02:29
I have the first table, is there any way to select from there and generate the second table output?

[url=http://www.imagechicken.com][/url]

Thank you very much.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-02-03 : 04:18:27
yup. see below


DECLARE @List varchar(3000)

SELECT @List = COALESCE(@List + '],[','') + Val
FROM (SELECT A as Val FROM Table
UNION
SELECT B FROM Table
UNION
SELECT C FROM Table
)t

SET @SQL='SELECT *
FROM
(
SELECT Key,Cat,Val
FROM Table t
UNPIVOT ( Val FOR Cat IN ([A],[B],[C]))u
)m
PIVOT (MAX(Cat) FOR Val IN ([' + @List + '])p'

EXEC (@Sql)

Go to Top of Page

pacolim
Starting Member

11 Posts

Posted - 2010-02-03 : 04:32:44
receive this error message:
Incorrect syntax near 'p'.
Go to Top of Page

pacolim
Starting Member

11 Posts

Posted - 2010-02-03 : 04:50:53
oh, it just missing one close bracket

PIVOT (MAX(Cat) FOR Val IN ([' + @List + ']))p'

It's working!! thanks a lot visakh16
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-02-03 : 06:21:52
welcome
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-02-03 : 06:23:15
Also refer
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -