Introduction
Pivot and unpivot help you change how data is shown. Pivot turns rows into columns, and unpivot turns columns into rows. This makes data easier to read or analyze.
/* Pivot syntax (example in SQL Server) */ SELECT <columns>, [PivotColumn1], [PivotColumn2], ... FROM ( SELECT <columns>, <pivot_column>, <value_column> FROM <table> ) AS SourceTable PIVOT ( SUM(<value_column>) FOR <pivot_column> IN ([PivotColumn1], [PivotColumn2], ...) ) AS PivotTable; /* Unpivot syntax (example in SQL Server) */ SELECT <columns>, UnpivotColumn, UnpivotValue FROM ( SELECT <columns>, [Column1], [Column2], ... FROM <table> ) AS SourceTable UNPIVOT ( UnpivotValue FOR UnpivotColumn IN ([Column1], [Column2], ...) ) AS UnpivotTable;
/* Pivot example: Show total sales per product per year */ SELECT Year, [Apples], [Oranges], [Bananas] FROM ( SELECT Year, Product, Sales FROM SalesData ) AS Source PIVOT ( SUM(Sales) FOR Product IN ([Apples], [Oranges], [Bananas]) ) AS PivotTable;
/* Unpivot example: Convert monthly sales columns into rows */ SELECT Year, Month, Sales FROM ( SELECT Year, Jan, Feb, Mar FROM MonthlySales ) AS Source UNPIVOT ( Sales FOR Month IN ([Jan], [Feb], [Mar]) ) AS UnpivotTable;
CREATE TABLE SalesData (Year INT, Product VARCHAR(20), Sales INT); INSERT INTO SalesData VALUES (2023, 'Apples', 100), (2023, 'Oranges', 150), (2023, 'Bananas', 120), (2024, 'Apples', 130), (2024, 'Oranges', 160), (2024, 'Bananas', 140); SELECT Year, [Apples], [Oranges], [Bananas] FROM ( SELECT Year, Product, Sales FROM SalesData ) AS Source PIVOT ( SUM(Sales) FOR Product IN ([Apples], [Oranges], [Bananas]) ) AS PivotTable;
PIVOT operation in SQL?Q1, Q2, Q3 into rows in SQL Server?Sales with columns Product, Year, Quarter, Amount, what will be the result of this query?SELECT * FROM Sales PIVOT (SUM(Amount) FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])) AS Pvt;
SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN (Q1, Q2, Q3)) AS Unpvt;
MonthlySales with columns Store, Jan, Feb, Mar representing sales per month. You want to create a report listing Store, Month, Sales rows. Which SQL approach correctly unpivots this data?SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; uses correct syntax for this.SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; [OK]Pass the test and this pattern moves unknown