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
有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top