SqlServer 2017+版本可以使用如下语句
SELECT GroupColumn, STRING_AGG(TargetColumn, ',') WITHIN GROUP (ORDER BY TargetColumn) AS MergedStrings FROM YourTable GROUP BY GroupColumn;
对于2017版本之前,可以使用FOR XML PATH
方法:
SELECT GroupColumn, STUFF( (SELECT ', ' + TargetColumn FROM YourTable t2 WHERE t2.GroupColumn = t1.GroupColumn ORDER BY TargetColumn FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS MergedStrings FROM YourTable t1 GROUP BY GroupColumn;