What does it mean to unpivot data, and how is it essentially the opposite operation of pivoting?
Short answer
Unpivoting transforms data from a column based format back into a row based format, taking several separate columns and converting them into rows with a category label and a corresponding value, which is useful when you receive data in a wide, spread out format but need it in a…
Advertisement
AModel answer
Unpivoting transforms data from a column based format back into a row based format, taking several separate columns and converting them into rows with a category label and a corresponding value, which is useful when you receive data in a wide, spread out format but need it in a more normalized, row based structure for further processing.
SELECT ProductId, MonthName, Amount
FROM MonthlySales
UNPIVOT (
Amount FOR MonthName IN ([January], [February], [March])
) AS unpvt;Real-world example
A data migration process receives sales data with separate columns for each month, and uses UNPIVOT to convert it back into a clean, normalized row based format before loading it into the target system.
Likely follow-ups
- What data type restrictions apply to the columns being unpivoted?
- Can UNPIVOT handle a source table with a very large number of columns to convert?
Related topics