How to get the values of column in SQL comma separ

2019-08-03 08:52发布

问题:

This question already has an answer here:

  • group_concat in SQL Server 2008 [duplicate] 2 answers

Hi my original data is as below

Id   | Value
-----+------
0001 | IN
0001 | ME
0001 | OH
0001 | ON
0002 | AC
0002 | ON
0002 | VI
0002 | ZO
0003 | ME
0003 | OO
0003 | PS
0003 | QA

Wanted to get the Data in

Id   | Value
-----+------
0001 | IN,ME,OH,ON
0002 | AC,ON,VI,ZO
0003 | ME,OO,PS,QA

in SQL server 2008

回答1:

This will work :

  SELECT
  t1.ID,
  MemberList = substring((SELECT ( ', ' + Value )
                       FROM your_table t2
                       WHERE t1.ID = t2.ID
                       ORDER BY 
                          ID,
                          Value
                       FOR XML PATH( '' )
                      ), 3, 1000 )FROM your_table t1
   GROUP BY ID


回答2:

    drop table #t

create table #t(id varchar(10),value char(10))

insert into #t values('0001','IN'),
('0001','ME'),
('0001','OH'),
('0001','ON'),
('0002','AC'),
('0002','ON'),
('0002','VI'),
('0002','ZO'),
('0003','ME'),
('0003','OO'),
('0003','PS'),
('0003','QA')

select distinct id,
    stuff((select ',' + CAST(t2.Value as varchar(10))
     from #t t2 where t1.id = t2.id 
     for xml path('')),1,1,'') as Value
from #t t1
group by id,Value

Output:

See Demo