Here's my query
select *
from Owner_TABLE
Results:
RollNumber People_ID Owner
-------------------------------------------
444201000100100 12 Jame Bond
444201000100100 14 Sam Doris
444201000100200 16 Jane Doe
444201000100200 17 John Morris
444201000100300 18 Mandy Noor
My objective here is to work out how I can combine the Owner into one row with the same RollNumber
?
Like =>
RollNumber Owner
----------------------------------------
444201000100100 James Bond, Sam Doris
Is this possible?
To give an example of what the comments have been pointing to:
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
The STUFF()
removes the remaining extra comma. The FOR XML
clause formats the result set...for XML.
Try this to get a better feel of FOR XML PATH
:
SELECT Owner
FROM ex
FOR XML PATH('')
Hi just want to share done the script and thanks for the people who posted their suggestions.
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
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.