可以使用以下方法将多行合并成一行:
FOR XML PATH('')
拼接行:SELECT STUFF((SELECT ',' + ColumnName
FROM TableName
FOR XML PATH('')), 1, 1, '') AS MergedColumn
FROM TableName
STRING_AGG
函数:SELECT STRING_AGG(ColumnName, ',') AS MergedColumn
FROM TableName
WITH RecursiveCTE AS (
SELECT ColumnName, ROW_NUMBER() OVER (ORDER BY ColumnName) AS RowNumber
FROM TableName
UNION ALL
SELECT r.ColumnName + ',' + t.ColumnName, t.RowNumber
FROM RecursiveCTE r
INNER JOIN TableName t ON t.RowNumber = r.RowNumber + 1
)
SELECT TOP 1 ColumnName
FROM RecursiveCTE
ORDER BY RowNumber DESC
OPTION (MAXRECURSION 0)
请注意,以上方法适用于SQL Server 2017或更高版本。在较早的版本中,可能需要使用其他方法来实现多行合并成一行。