我有一张如下表格
Code Attribute Value
--------------------------------------
USA Population 300M
USA Language US English
CANADA Population 30M
USA Capital DC
CANADA Language CA English
如何将表格旋转90度并进行查看,如下所示运行 查询 和 sp < / strong> 就可以了?
Code Language Population Capital
------------------------------------------------------
USA US English 300M DC
CANADA CA English 30M NULL
答案 0 :(得分:9)
您可以使用PIVOT
(对于SQL Server 2005 +):
SELECT *
FROM YourTable AS T
PIVOT (MIN(Value) FOR Attribute IN ([Language],[Population],[Capital]) AS PT
对于所有版本的SQL Server,您可以使用:
SELECT Code,
MIN(CASE WHEN Attribute = 'Language' THEN Value END) [Language],
MIN(CASE WHEN Attribute = 'Population' THEN Value END) [Population],
MIN(CASE WHEN Attribute = 'Capital' THEN Value END) [Capital]
FROM YourTable
GROUP BY Code