SELECT multiple rows from single column into single row

后端 未结 3 1342
傲寒
傲寒 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:45

    What you are looking for is something like SQL Server's FOR XML PATH('') which combines results as a rowset

    Select Person.Name, 
      (
         Select SkillName + ',' 
         From SkillLink 
         inner join skill on skill.id = skilllink.skillid
         Where SkillLink.PersonID = Person.ID FOR XML PATH('')
      )
    as Skills
    FROM Person 
    
    0 讨论(0)
  • 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 |
    
    0 讨论(0)
  • 2021-01-03 13:58

    What you are looking for is something like SQL Server's FOR XML PATH which combines results as a rowset

    0 讨论(0)
提交回复
热议问题