De Vonte De Vonte - 2 years ago 64
SQL Question

SQL convert from 3 to 2 columns

I am trying to convert 3 columns into 2. Is there a way I can do this with the example below or a different way?

For example.

Year Temp Temp1
2015 5 6


Into:

Year Value
Base 5
2015 6

Answer Source

You could use CROSS APPLY and row constructor:

SELECT s.*
FROM t
CROSS APPLY(VALUES('Base', Temp),(CAST(Year AS NVARCHAR(100)), Temp1)
           ) AS s(year,value);

LiveDemo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download