Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 505
TheProgrammer Avatar asked Jan 06 '23 03:01

TheProgrammer


2 Answers

This is called unpivot, pivot is the exact opposite(make 2 columns into more) .

You can do this with a simple UNION ALL:

SELECT 'Base',s.temp FROM YourTable s
UNION ALL
SELECT t.year,t.temp1 FROM YourTable t

This relays on what you wrote on the comments, if year is constant , you can replace it with '2015'

like image 186
sagi Avatar answered Jan 17 '23 21:01

sagi


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

like image 36
Lukasz Szozda Avatar answered Jan 17 '23 21:01

Lukasz Szozda