Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping data in comma separated format

Tags:

sql-server

I have a table called SampleData which looks like this:

 col1    col2     
    1       a       
    1       b       
    1       c      
    2       d       
    2       e
    3       f

I need the data in the below format:

col1    col2     
1       a,b,c           
2       d,e       
3       f

Is there a way of doing this using CTE as well?

like image 727
satyajit Avatar asked Aug 13 '26 07:08

satyajit


2 Answers

you can use STUFF if you are using SQL Server 2005 and above.

SELECT
     [col1],
     STUFF(
         (SELECT ',' + [col2]
          FROM Table1
          WHERE [col1] = a.[col1]
          FOR XML PATH ('')) , 1, 1, '')  AS col2
FROM Table1 AS a
GROUP BY [col1]
  • SQLFiddle Demo
like image 67
John Woo Avatar answered Aug 16 '26 06:08

John Woo


I think this is also useful to you.

Comma Seprate Value

like image 32
Hiren gardhariya Avatar answered Aug 16 '26 08:08

Hiren gardhariya