I\'m writing an export function, where I need to export contacts to Excel, and I\'ve run into a technical snag - or perhaps a gap in my SQL skills is closer to the truth. ;)
You can do it in a single query, though I don't know if the performance is good or bad.
SELECT [<group field 1>], [<group field 2>], [etc...], (
SELECT CAST([<field to list>] AS VARCHAR(MAX)) +
CASE WHEN (ROW_NUMBER() OVER (ORDER BY [<inner order-by REVERSED>]) = 1)
THEN '' ELSE ',' END
AS [text()]
FROM [<inner table>]
WHERE [<inner table join field>] = [<outer table join field>]
AND [<inner conditions>]
ORDER BY [<inner order-by>]
FOR XML PATH('')) AS [<alias>]
FROM [<outer table]
WHERE [<outer conditions>]
That CASE statement inside is just to remove the last comma from the list--you have to ORDER BY something for the inner query and then reverse that ORDER BY in the CASE statement.