T-SQL 实现行转列
问题:
我正在寻找一种有效的方式将行转换为SQL服务器中的列
例如,通过下表如何构建出预期结果表。
Id Value ColumnName
1 John FirstName
2 2.4 Amount
3 ZH1E4A PostalCode
4 Fork LastName
5 857685 AccountNumber
预期结果
FirstName Amount PostalCode LastName AccountNumber
John 2.4 ZH1E4A Fork 857685
解答:
有多种方法可以将数据从多行转换为列。 在SQL Server中,可以使用PIVOT函数将数据从行转换为列:
SELECT Firstname, Amount, PostalCode, LastName, AccountNumber FROM (SELECT value, columnname FROM yourtable) d PIVOT (MAX(value) FOR columnname IN (Firstname, Amount, PostalCode, LastName, AccountNumber)) piv
如果您有未知数目的列名称要转置,那么您可以使用动态SQL:
DECLARE @cols AS nvarchar(max), @query AS nvarchar(max) SELECT @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) FROM yourtable GROUP BY ColumnName, id ORDER BY id FOR xml PATH (''), TYPE) .value('.', 'NVARCHAR(MAX)'), 1, 1, '') SET @query = N'SELECT ' + @cols + N' from ( select value, ColumnName from yourtable ) x
pivot ( max(value) for ColumnName in (' + @cols + N')) p ' EXEC sp_executesql @query;
如果不想使用PIVOT函数,则可以使用带有CASE表达式的聚合函数:
select max(case when columnname = 'FirstName' then value end) Firstname, max(case when columnname = 'Amount' then value end) Amount, max(case when columnname = 'PostalCode' then value end) PostalCode, max(case when columnname = 'LastName' then value end) LastName, max(case when columnname = 'AccountNumber' then value end) AccountNumber from yourtable