SQL converts 3 to 2 columns

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

For instance.

Year   Temp   Temp1
2015    5       6

AT:

Year   Value
Base     5
2015     6
+4
source share
3 answers

You can use the constructor CROSS APPLYand row:

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

LiveDemo

+2
source

This is called univot, pivot is the exact opposite (add 2 columns).

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 refers to what you wrote in the comments, if the year is constant, you can replace it with "2015"

+5
source

. UNION ALL .

I suggest reading this thread Convert columns to rows with their corresponding data on sql server , as it provides much more information, and you can try and check how different solutions will work for you.

+2
source

All Articles