我有一张这样的表
TableX
Id ServiceID
1 10
1 20
1 30
2 15
2 25
2 35
和表变量@TableA
declare @TableA table
(
Id int primary key,
ServiceIdList varchar(max)
)
我需要@TableA看起来像这样
Id ServiceIdList
1 10,20,30
2 15,25,35
但我无法弄清楚insert语句的语法。如果可能的话,我想使用COALESCE而不是STUFF。有人知道怎么做吗? 像
这样的东西Insert @TableA
select distinct X.Id,
coalesce(@TableA.ServiceIdList + ',', '') + cast(TableX.ServiceId as varchar)
from TableX X
group by X.Id, X.ServiceId
非常感谢你提前
答案 0 :(得分:2)
Insert @TableA
Select A.ID
,ServiceIdList = (Select Stuff((Select Distinct ',' +cast(ServiceID as varchar(25)) From YourTable Where ID=A.ID For XML Path ('')),1,1,'') )
From (Select Distinct ID From YourTable ) A
返回
ID ServiceIdList
1 10,20,30
2 15,25,35