在查询中将行与相同的id组合在一起

时间:2015-03-24 15:29:30

标签: sql sql-server tsql

这是我的查询

select * 
from Owner_TABLE

结果:

RollNumber         People_ID   Owner
-------------------------------------------
444201000100100      12        Jame Bond
444201000100100      14        Sam Doris
444201000100200      16        Jane Doe
444201000100200      17        John Morris
444201000100300      18        Mandy Noor

我的目标是找出如何将所有者合并为一行RollNumber

喜欢=>

RollNumber         Owner
----------------------------------------
444201000100100    James Bond, Sam Doris

这可能吗?

2 个答案:

答案 0 :(得分:0)

举例说明评论指出的内容:

WITH ex as
(SELECT '444201000100100' as 'RollNumber', '12' as 'PeopleID', 'Jame Bond' as 'Owner'
UNION
SELECT '444201000100100', '14', 'Sam Doris'
UNION
SELECT '444201000100200', '16', 'Jane Doe'
UNION
SELECT '444201000100200', '17', 'John Morris'
UNION
SELECT '444201000100100', '18', 'Mandy Noor'
) 
SELECT RollNumber, STUFF((SELECT ', ' + e.Owner
                          FROM ex e
                          WHERE e.RollNumber = a.RollNumber
                          FOR XML PATH('')
                          ),1,2,'') as 'Owners'
FROM ex a
GROUP BY RollNumber

STUFF()删除剩余的额外逗号。 FOR XML子句为XML格式化结果集....

尝试此操作以更好地了解FOR XML PATH

SELECT Owner
FROM ex
FOR XML PATH('')

答案 1 :(得分:0)

您只想分享完成脚本并感谢发布他们建议的人。

select p1.RollNumber,
(SELECT  FullName+', '  
FROM [dbo].[view_Owners_roll] p2 
WHERE
p1.RollNumber=p2.RollNumber 
for XML path(''),type).value('.','varchar(max)') 
as Name  from [dbo].[view_Owners_roll] p1 group by RollNumber