Output a comma-separated list in a column in SQL Server [duplicate]

拥有回忆 提交于 2019-11-28 11:12:49

问题


Possible Duplicate:
Simulating group_concat MySQL function in SQL Server 2005?

What's the best way to achieve this? Edit: in MSSQL 2005

Table

a   |  b
------------
x   |  1
x   |  4
y   |  6
y   |  1

Query:

SELECT ? FROM Table

so that output is :

a   | ListOfB
------------
x   | 1, 4
y   | 6, 1

回答1:


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

See SQL Fiddle with Demo



来源:https://stackoverflow.com/questions/13052994/output-a-comma-separated-list-in-a-column-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!