Avatar of Soalga
Soalga
 asked on

Swap Rows / Cols in a SQL Server 2005 Query / View

I have a table under SQL Server 2005 with two columns (col1, col2) and this table have about 10 records, so the table look like this:

COL1        COL2
=============
val1          val_1
val2          val_2
...
valN          val_N

what's the best way to swap rows for cols to obtain some like this in a view:

val1     val2      ...   valN
====================
val_1   val_2   ...   val_N,

where the values of COL1 becomes the column names of the result, and the values of COL2 the values for each new column.
Microsoft SQL Server 2005

Avatar of undefined
Last Comment
ptjcb

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ptjcb

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Soalga

ASKER
well... thx... i do that... like this

SELECT * FROM <table>
      PIVOT (
            max(COL2)
            FOR COL1 IN([COL1], [COL2], ..., [COLN])
      ) AS PVT

But, what about if i have an unknown number of columns, i mean, i have "about" 10 records (that becomes the columns), how can i determine the IN(<cols>) sintax?
SOLUTION
ptjcb

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
ptjcb

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61