在SQL Server的列中输出逗号分隔列表
问题描述:
这是最好的方法是什么?编辑:在MSSQL 2005中
What's the best way to achieve this? in MSSQL 2005
表
a | b
------------
x | 1
x | 4
y | 6
y | 1
查询:
SELECT ? FROM Table
,使输出为:
a | ListOfB
------------
x | 1, 4
y | 6, 1
答
c $ c> FOR XML PATH :
In SQL Server you can use FOR XML PATH
:
select distinct a,
stuff(
(
select ','+ cast(b as varchar(10))
from table1 t2
where t1.a = t2.a for XML path('')
),1,1,'') ListOfB
from table1 t1
a href =http://sqlfiddle.com/#!3/83f96/6> SQL示范演示
See SQL Fiddle with Demo