2

I have a table that lists items and section that they belong to and the subsections within that. Each item can belong to any number of sections and subsections and doesn't have to belong to all. Roughly like:

Item|Section|SubSection
1   |1      |1a
1   |1      |1b
1   |1      |1c
2   |1      |1b
1   |2      |2a
1   |2      |2b
2   |2      |2a
2   |2      |2c

Is there a select string or function that would allow me to pull out the Item, Section and then a string with the subsection with a comma or other delimiter.

i.e the results from above would look like:

Item|Section|SubSectionString
1   |1      |1a,1b,1c
2   |1      |1c
1   |2      |2a,2b
2   |2      |2a,2c

Kind regards

Matt

Matt Bartlett
  • 348
  • 1
  • 3
  • 21

1 Answers1

3

Try with stuff funtion:

  SELECT item,section,  abc = STUFF(
                 (SELECT ',' + SubSection
                  FROM table1 t1
                  WHERE t1.item = t2.item and t1.section= t2.section
                  FOR XML PATH (''))
                 , 1, 1, '') from table1 t2
    group by item,section;
Fahmi
  • 37,315
  • 5
  • 22
  • 31