Suppose I got a table with emails and category and I want to group the emails based on category, the following sql statement can be simply be used:
DECLARE @Email AS TABLE
(
Category INT,
Email VARCHAR(MAX)
)
INSERT INTO @Email
SELECT DISTINCT te.Category,
(
SELECT Email + ','
FROM @TempEmail te2
WHERE te2.Category = te.Category
ORDER BY Email
FOR XML PATH('')
) AS Email
FROM @TempEmail te