尝试这个
Declare @t Table([UserID] int, [AddressLine1] varchar(20), [AddressLine2] varchar(20), [Phone] int);
INSERT INTO @t VALUES
(1, 'First Street', 'Somewhere', 123),
(1, 'Second Street', 'Somewhere2', 124),
(2, '32th Street', 'Somewhere', 125),
(2, '24th Street', 'Somewhere3', 126),
(2, '25th Street', 'Somewhere4', 127);
SELECT
[UserID]
, [New Address] =
STUFF((
SELECT ','
+ [AddressLine1]
+ ', '
+ [AddressLine2]
+ ', '
+ CAST([Phone] AS VARCHAR(10))
FROM @t AS t2
WHERE t1.UserID = t2.UserID
FOR XML PATH('')),1,1,'')
FROM @t t1
GROUP BY t1.[UserID]
//结果
用户 ID 新地址
1 First Street, Somewhere, 123,Second Street, Somewhere2, 124
2 32th Street, Somewhere, 125,24th Street, Somewhere3, 126,25th Street, Somewhere4, 127
除了这里描述的方法之外,还有许多其他方法可以解决同样的问题。值得一提的是,在 Transact-SQL文章中查看 Concatenating Row Values。这是一篇很棒的文章,请花一些时间来阅读它(如果你还没有这样做的话)。
希望这可以帮助