您可以使用 SQL-Servers XML 扩展将行连接到列:
SELECT ID,
UserName,
OfficeNumber = STUFF(( SELECT ',' + CAST(OfficeNumber AS VARCHAR(3))
FROM YourTable b
WHERE a.UserName = b.UserName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM ( SELECT ID = MIN(ID), UserName
FROM YourTable
GROUP BY UserName
) a;
SQL Fiddle 示例
SO上还有一个问题,有人问过这个方法如何工作的复杂性,也有几个答案,这里就不重复解释了。
编辑
只是似乎您没有为每个用户名使用最小 ID,而是重新分配一个新号码作为 ID,如果要根据每个用户名的最低原始 ID 重新分配 ID,那么您可以使用:
SELECT ID,
UserName,
OfficeNumber = STUFF(( SELECT ',' + CAST(OfficeNumber AS VARCHAR(3))
FROM YourTable b
WHERE a.UserName = b.UserName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM ( SELECT ID = ROW_NUMBER() OVER(ORDER BY MIN(ID)), UserName
FROM YourTable
GROUP BY UserName
) a;
SQL-Fiddle 示例
或者,如果它按字母顺序排列,您可以使用
SELECT ID = ROW_NUMBER() OVER(ORDER BY a.UserName),
UserName,
OfficeNumber = STUFF(( SELECT ',' + CAST(OfficeNumber AS VARCHAR(3))
FROM YourTable b
WHERE a.UserName = b.UserName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM YourTable a
GROUP BY a.UserName
SQL-Fiddle 示例