Tuesday, March 13, 2012

T-SQL: Aggregate a column to a comma delimited list

I commonly encounter situations where it is useful to select a comma delimited list as an aggregate in a grouped query. This is a well known problem and yet each time I run across it I have to look something up to solve it.

The following is a detailed breakdown of the solution from the msdn archive.

The scenario I'm covering here is the need to aggregate all the IDs in a joined table into a single column on the master table. We'll use a table structure like this:
  Id int NOT NULL identity,
  Name varchar(50) NOT NULL,
  Children varchar(256) NULL,
  Id int NOT NULL identity,
  ParentId int NOT NULL,
  Name varchar(50) NOT NULL
Create some sample data:
INSERT INTO Parent (Name)
VALUES ('Parent 1'), ('Parent 2'), ('Parent 3')
INSERT INTO Child (ParentId, Name)
VALUES (1, 'Child 1'), (1, 'Child 2'), (1, 'Child 3'), (2, 'Child 4'), (2, 'Child 5'), (3, 'Child 6'), (3, 'Child 7'), (3, 'Child 8'), (3, 'Child 9')
Now we can update the Children column on Parent with this:
t AS (SELECT p1.Id, Children = (
    SELECT (',' + convert(varchar, c2.Name ))
    FROM Parent p2
      JOIN Child c2 ON p2.Id = c2.ParentId
    WHERE p2.Id = p1.Id
    ORDER BY c2.Id
    FOR XML PATH( '' )
  ) + ','
  FROM Parent p1
    JOIN Child c1 ON p1.Id = c1.ParentId
  GROUP BY p1.Id)
SET Children = t.Children
FROM Parent p
  JOIN t ON t.Id = p.Id
And the results look like:
Id | Name | Children
1 | Parent 1 | ,Child 1,Child 2,Child 3,
2 | Parent 2 | ,Child 4,Child 5,
3 | Parent 3 | ,Child 6,Child 7,Child 8,Child 9,