如何将列值以逗号分隔,包括id

时间:2016-12-30 16:04:20

标签: sql sql-server database

我有一个要求,我当前的表有

id     value
1      newyork
1      boston
1      dallas

我需要以下输出

id      value
1       newyork, boston, dallas

1 个答案:

答案 0 :(得分:2)

Declare @YourTable table(ID int,[value] varchar(50))
Insert Into @YourTable values
(1,'newyork'),
(1,'boston'),
(1,'dallas')

Select A.ID
      ,Value  = (Select Stuff((Select Distinct ',' +value From @YourTable Where ID=A.ID For XML Path ('')),1,1,'') )
 From (Select Distinct ID From @YourTable) A

返回

ID  Value
1   boston,dallas,newyork