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
 Transposing Rows of Data to columns

Author  Topic 

srattman72
Starting Member

4 Posts

Posted - 2011-08-08 : 12:43:29
Hello All -

Relatively new to SQL coding and had a question on how to transpose data. Here is an example of what I am trying to do:

ID Drug Alt Drug
001 A Z
001 B Y
001 C X
002 B Z
002 D W

I need my final output to look like the following:

ID Drug#1 Alt Drug#1 Drug#2 Alt Drug#2 Drug #3 Alt Drug#3
001 A Z B Y C X
002 B Y D W

This needs to be done for all ID's that have up to 10 different drugs. Any and all help is appreciated.

Thanks,

Shane

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-08 : 13:00:42
[code]
SELECT ID,
MAX(CASE WHEN Rn=1 THEN Drug ELSE NULL END) AS Drug1,
MAX(CASE WHEN Rn=1 THEN AltDrug ELSE NULL END) AS AltDrug1,
MAX(CASE WHEN Rn=2 THEN Drug ELSE NULL END) AS Drug2,
MAX(CASE WHEN Rn=2 THEN AltDrug ELSE NULL END) AS AltDrug2,
MAX(CASE WHEN Rn=3 THEN Drug ELSE NULL END) AS Drug3,
MAX(CASE WHEN Rn=3 THEN AltDrug ELSE NULL END) AS AltDrug3
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Drug) AS Rn,*
FROM table
)t
GROUP BY ID
[/code]

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

Go to Top of Page
   

- Advertisement -