I am working in SQL Server 2008 R2
I have a parent table and a child table (one to many relationship). What I would like to do is query the parent table but also include a field from the child table aggregated into a comma separated string.
So if the parent table is called Person with an ID field开发者_JAVA技巧, FirstName and LastName and the child table is called Kids with and ID field, a ParentID field (FK to the parent table), FirstName, and LastName...I would like to return a dataset similar to this:
ParentFirstName = Mike
ParentLastName = Davis KidsFirstNames = Suzy, David, AlexI thought there was a way to do this with the For XML Path but I cannot remember the syntax.
Thanks in advance.
Have a look at this example
declare @YourTable table (BirthDay datetime, PersonName varchar(20))
insert into @YourTable VALUES ('1-10-2010', 'Joe' )
insert into @YourTable VALUES ('2-10-2010', 'Bob' )
insert into @YourTable VALUES ('2-10-2010', 'Alice')
SELECT
p1.BirthDay
,STUFF(
(SELECT
', ' + p2.PersonName
FROM @YourTable p2
WHERE p2.BirthDay=p1.BirthDay
ORDER BY p2.PersonName
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS PersonNames
FROM @YourTable p1
GROUP BY p1.BirthDay
精彩评论