Link to home
Start Free TrialLog in
Avatar of sqlagent007
sqlagent007Flag for United States of America

asked on

TSQL how to concatenate several row results into one row

I have a table that stores user comments, the table is very simple 3 column table: commentid, customerid, comment. I need to show all comments made by one customer as 1 line. When I do something like:
SELECT comment FROM [COMMENTS] WHERE customerid=12
I get 21 rows of all the historical comments. I need to concatenate all these entries into 1 row for output.

Any ideas?

Thanks experts!
ASKER CERTIFIED SOLUTION
Avatar of vasto
vasto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Stuff will also allow you to get a list of customers with their comments:

SELECT cst.customerid,
         Stuff((SELECT ', ' + c.comment FROM COMMENTS c WHERE c.customerid = cst.customerid For XML PATH ('')),1,1,'')
FROM  (SELECT DISTINCT customerid FROM COMMENTS ) cst
Avatar of sqlagent007

ASKER

Both were great! Thanks guys!