标签:pre ast 函数 post pos group by arc 动态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
标签:pre ast 函数 post pos group by arc 动态sql 如何
原文地址:http://www.cnblogs.com/bi-info/p/6215215.html