简体   繁体   中英

SQL Server 2005 pivot table

I want to pivot a column in SQL Server 2005. I'm pretty sure there is XML way to get it done but can't figure it out. Here is a table:

ID    Class
1     20002
1     20003
1     20004
2     20003
2     20012

Desired value is:

ID    Class
1     20002,20003,20004
2     20003,20012

Thanks in advance

I am not sure PIVOT (or UNPIVOT) are what you are looking for. Below is some code that I use when I need to get a CSV list embedded in a query. Hope it helps!

SELECT DISTINCT 
        ID
      , Class = STUFF(
                       cast(
                            (select ', ' + cast(Class as nvarchar) 
                             from TableName t2 
                             WHERE t2.ID = t1.ID 
                             for xml path('')) as nvarchar(2000))
                ,1,2, N'')
FROM TableName t1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM