De Vonte De Vonte - 7 months ago 10
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

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