Rod Harten - Friday, April 28, 2017 6:38 PM
I think this will give you what you're looking for.
WITH cteData AS (
SELECT n.Name, s.State
FROM #names n
INNER JOIN #name_states ns ON ns.NameID = n.NameID
INNER JOIN #states s ON ns.StateID = s.StateID
),
cteNames AS (
SELECT DISTINCT Name
FROM #names
)
SELECT Name,
StatesList = STUFF((SELECT ',' + d.State
FROM cteData d
WHERE d.Name = cteNames.Name
ORDER BY d.State
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, '')
FROM cteNames
ORDER BY Name;
There are many approaches to creating a delimited list, but Wayne Sheffield's article at http://www.sqlservercentral.com/articles/comma+separated+list/71700/ is the approach I prefer. This is the technique above.
Edit: Please forgive the indenting of the code, but I still haven't gotten the knack of the new SQL editor on SSC. I tried to get it close.