如何使逗号分隔值

时间:2014-03-24 05:08:35

标签: sql sql-server tsql

这是我的表结构

    create table #t(PK int,col1 varchar(10),col2 varchar(10))
  insert into #t values(1,'A','a'),(2,'B','b'),(3,'C','c'),(4,'A','d'),(5,'A','e'),(6,'B','f'),(88,'F','l'),(7,'C','g'),(8,'C','h'),(9,'D','k')

输出列必须如下所示

col1    col2
A          a,d,e
B          b,f
C          c,g,h
D          k
F          l

我怎么得到这样的输出?

2 个答案:

答案 0 :(得分:1)

drop table #t
create table #t(PK int,col1 varchar(10),col2 varchar(10))
insert into #t values(1,'A','a'),(2,'B','b'),(3,'C','c'),(4,'A','d'),(5,'A','e'),(6,'B','f'),(88,'F','l'),(7,'C','g'),(8,'C','h'),(9,'D','k')

select col1,SUBSTRING(d.col2,1,len(d.col2)-1)col2
from 
(
    select distinct col1 from #t
)a
cross apply(
select [col2]+',' from #t B where A.col1=B.col1
for xml path('')
)d (col2)

DEMO

答案 1 :(得分:0)

试试这个

select distinct t.[col1],
  STUFF((SELECT distinct ', ' + t1.col2
         from yourtable t1
         where t.[col1] = t1.[col1]
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') department
from yourtable t;

Fiddle Demo