4

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
Taryn
  • 242,637
  • 56
  • 362
  • 405
TheProgrammer
  • 1,314
  • 5
  • 22
  • 44

3 Answers3

5

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'

sagi
  • 40,026
  • 6
  • 59
  • 84
2

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

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
2

There is more than one answer to your question. Using UNION ALL seems to be the most simple solution.

I suggest reading this thread Converting Columns into rows with their respective data in sql server, as it provides a lot more details, and you can try and test how different solutions will work for you.

Community
  • 1
  • 1
TodorS
  • 406
  • 4
  • 4