将同一列的两个或多个条目显示为一个字符串

时间:2018-01-07 21:01:38

标签: sql sql-server database

我想显示我的数据库中的每个人以及此人所有的电影,我想摆脱双重条目。有没有办法让条目看起来像

[Name] | [Movie title] | [Job1] "/" [job2?] "/" [job3?] 

等?

enter image description here

1 个答案:

答案 0 :(得分:3)

示例

Select PersonName
      ,Title
     , Jobs  = Stuff((Select Distinct ' / ' +Job From @YourTable Where PersonName=A.PersonName and Title=A.Title For XML Path ('')),1,3,'') 
 From (
        Select Distinct 
               PersonName
              ,Title  
         From @YourTable
      ) A

<强>返回

PersonName      Title               Jobs
Arnie Hammer    The Loan Ranger     Actor
Dule Hill       Psych: The Movie    Actor / Producer
Jim Parsons     NULL                NULL