Mertez
Mertez

Reputation: 1131

Rotate SQL Table

I have a table like below

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

How can I rotate table for 90 degrees and make a view like below to run query and sp on it?

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

Upvotes: 2

Views: 7003

Answers (1)

Lamak
Lamak

Reputation: 70638

You could use PIVOT (for SQL Server 2005+):

SELECT *
FROM YourTable AS T
PIVOT (MIN(Value) FOR Attribute IN ([Language],[Population],[Capital]) AS PT

For all version of SQL Server you can use this:

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

Upvotes: 10

Related Questions