如何在SQL逗号分隔中获取列的值

时间:2014-02-06 13:17:54

标签: sql sql-server-2008

您好我的原始数据如下

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

想要获取数据

Id   | Value
-----+------
0001 | IN,ME,OH,ON
0002 | AC,ON,VI,ZO
0003 | ME,OO,PS,QA
SQL Server 2008中的

2 个答案:

答案 0 :(得分:0)

这将有效:

  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

答案 1 :(得分:0)

    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

输出:

enter image description here

See Demo