2

我有一张如下表

Code        Attribute        Value
--------------------------------------
USA         Population       300M
USA         Language         US English
CANADA      Population       30M
USA         Capital          DC
CANADA      Language         CA English

如何将表格旋转 90 度并制作如下视图以在其上运行查询sp

Code        Language        Population       Capital
------------------------------------------------------
USA         US English         300M              DC
CANADA      CA English          30M              NULL
4

1 回答 1

10

您可以使用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
于 2012-07-23T22:09:55.523 回答