可以使用以下方法將多行合并成一行:
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或更高版本。在較早的版本中,可能需要使用其他方法來實現多行合并成一行。