One of the most common questions I receive in email is how to group multiple column data in comma separate values in a single row grouping by another column.
I have previously blogged about it in following two blog posts. However, both aren’t addressing the following exact problem.
Here is the sample script to build the sample dataset.
CREATE TABLE TestTable (ID INT, Col VARCHAR(4))
INSERT INTO TestTable (ID, Col)
SELECT 1, 'A'
SELECT 1, 'B'
SELECT 1, 'C'
SELECT 2, 'A'
SELECT 2, 'B'
SELECT 2, 'C'
SELECT 2, 'D'
SELECT 2, 'E'
Here is the solution which will build an answer to the above question.
-- Get CSV values
SELECT t.ID, STUFF(
(SELECT ',' + s.Col
FROM TestTable s
WHERE s.ID = t.ID
FOR XML PATH('')),1,1,'') AS CSV
FROM TestTable AS t
GROUP BY t.ID
I hope this is an easy solution. I am going to point to this blog post in the future for all the similar questions.
Final Clean Up Act
-- Clean up
DROP TABLE TestTable
Here is the question back to you –
Is there any better way to write above script? Please leave a comment and I will write a separate blog post with due credit.
Reference: Pinal Dave (http://blog.sqlauthority.com)