Skip to main content
1 of 7
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619

This is relatively trivial to do with a correlated subquery. You can't use the COALESCE method highlighted in the blog post you mention unless you extract that to a user-defined function (or unless you only want to return one row at a time). Here is how I typically do this:

DECLARE @x TABLE 
(
  id INT, 
  row_num INT, 
  customer_code VARCHAR(32), 
  comments VARCHAR(32)
);

INSERT @x SELECT 1,1,'Dilbert','Hard'
UNION ALL SELECT 1,2,'Dilbert','Worker'
UNION ALL SELECT 2,1,'Wally','Lazy';

SELECT id, customer_code, STUFF((SELECT ' ' + comments 
    FROM @x AS x2 WHERE id = x.id FOR XML PATH(''), 
    TYPE).value('.', 'nvarchar(max)'), 1, 1, '')
FROM @x AS x
GROUP BY id, customer_code
ORDER BY id;
Aaron Bertrand
  • 181.5k
  • 28
  • 402
  • 619