SELECT multiple rows from single column into single row

后端 未结 3 1341
傲寒
傲寒 2021-01-03 13:25

I want to write an SQL Server query that will retrieve data from the following example tables:

Table: Person
ID      Name
--      ----
1       Bill
2       B         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 13:51

    You would use FOR XML PATH for this:

    select p.name,
      Stuff((SELECT ', ' + s.skillName 
             FROM skilllink l
             left join skill s
               on l.skillid = s.id 
             where p.id = l.personid
             FOR XML PATH('')),1,1,'') Skills
    from person p
    

    See SQL Fiddle with Demo

    Result:

    | NAME |            SKILLS |
    ----------------------------
    | Bill | Telepathy, Karate |
    |  Bob |            (null) |
    |  Jim |         Carpentry |
    

提交回复
热议问题