TSQL - Unpivot multiple columns

SvenB picture SvenB · May 13, 2013 · Viewed 9.3k times · Source

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.

Answer

Martin Smith picture Martin Smith · May 13, 2013
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