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
  • 234,956
  • 54
  • 359
  • 399
TheProgrammer
  • 1,118
  • 3
  • 17
  • 38

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
  • 38,630
  • 5
  • 53
  • 82
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
  • 139,860
  • 19
  • 198
  • 228
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