3

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?

4

2 回答 2

5

如果您正在使用及以上,则可以使用STUFF 。SQL Server 2005

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]
于 2013-07-21T11:33:41.447 回答
1

我认为这对您也很有用。

逗号分隔值

于 2013-07-22T05:08:22.373 回答