Skip to content

UNPIVOT

CREATE TABLE #Temp
(
Item VARCHAR(50),
Jan INT,
Feb INT,
Mar INT
)
INSERT INTO #Temp
VALUES
('Apples', 10, 20, 30),
('Oranges', 40, 50, 60)
SELECT Item, Month, Sales
FROM
(
SELECT Item, Jan, Feb, Mar
FROM #Temp
) as p
UNPIVOT
(
Sales FOR Month IN (Jan, Feb, Mar)
) AS unpvt
DROP TABLE #Temp
Item | Month | Sales
---------|-------|-------
Apples | Jan | 10
Apples | Feb | 20
Apples | Mar | 30
Oranges | Jan | 40
Oranges | Feb | 50
Oranges | Mar | 60

This example first creates a temporary table, #Temp, with an item column and sales data columns for each of three months - January, February, and March. Then, UNPIVOT is used to convert these months’ columns into row values under the ‘Month’ column, along with the corresponding sales values under the ‘Sales’ column for each item. This turns the data from a ‘wide’ format to a ‘long’ format. At last, the temporary table #Temp is dropped.