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
 converting rows into columns

Author  Topic 

rameshgoudd
Starting Member

13 Posts

Posted - 2008-06-22 : 02:11:43
hi,

i have the 4rows in one table those are book names...

book1
book2
book3
book4


i have the other table..consisting of usenames

in the output i need like this

username1 book1 book2 book3 book4
username2 book1 book2 book3 book4

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-22 : 03:09:27
Something like:-
 
SELECT u.username,
MAX(CASE WHEN b.RowNo=1 THEN b.bookname ELSE NULL END) AS book1,
MAX(CASE WHEN b.RowNo=2 THEN b.bookname ELSE NULL END) AS book2,
MAX(CASE WHEN b.RowNo=3 THEN b.bookname ELSE NULL END) AS book3,
MAX(CASE WHEN b.RowNo=4 THEN b.bookname ELSE NULL END) AS book4
FROM YourUsertable u
INNER JOIN
(SELECT ROW_NUMBER() OVER(PARTITION BY userid ORDER BY bookid) AS RowNo,*
FROM Yourbooktable) b
ON b.userid=u.userid
GROUP BY u.usernme


please replace the table & column names with you actual ones.
Go to Top of Page
   

- Advertisement -