0

Given the following simple example

create table #example (
ProductID int,
ProductName varchar(100),
CustomerID int
)

insert #example values 
    (1,'Product 1',100),
    (2,'Product 2',100),
    (3,'Product 3', 101),
    (3,'Product 3', 102)

I want to see a result set that has CustomerID, ProductNamesBought where the products are comma separated. e.g.

CustomerID ProductNamesBought
========== ====================
100        Product 1, Product 2
101        Product 3
102        Product 3
Mark Allison
  • 6,838
  • 33
  • 102
  • 151

1 Answers1

1
SELECT  e.CustomerID, 
        STUFF((SELECT ','+ProductName FROM #example WHERE e.CustomerID = CustomerID FOR XML PATH('')),1,1,'') as ProductNamesBought
FROM #example e
GROUP BY e.CustomerID

Output:

CustomerID  ProductNamesBought
100         Product 1,Product 2
101         Product 3
102         Product 3
gofr1
  • 15,741
  • 11
  • 42
  • 52