Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Unpivot multiple columns

How can I unpivot multiple columns in "one"?

Right now I have an unpivot for each column but this creates a lot of empty rows.

See the screenshot please. enter image description here

At the top you see the input data. At the moment I'm at the table in the middle with this code:

SELECT [ID], [RowNumber],  [Year], [Sales]  FROM (
        SELECT ID, RowNumber, [Sales 2013] as [2013], [Sales 2014] as [2014]
        FROM mytable) p     UNPIVOT (
        [Sales] FOR [Year] IN ([2013], [2014])  )AS unpvt ;

But I think it would be much better to get to the bottom table structure since the actual data contains more columns and more years to deal with.

Here's a Fiddle with the sample data.

Hope you can show me a way to get there. Thank you.

like image 317
SvenB Avatar asked Dec 27 '22 04:12

SvenB


1 Answers

SELECT [ID],
       [RowNumber],
       [Year],
       Sales,
       Budget
FROM   mytable
       CROSS APPLY (VALUES (2013, [Sales 2013], [Budget 2013]),
                           (2014, [Sales 2014], [Budget 2014]) ) 
                     V([Year], Sales, Budget) 

SQL Fiddle

like image 190
Martin Smith Avatar answered Jan 02 '23 10:01

Martin Smith