PIVOT and UNPIVOT are powerful SQL operations that transform data between row and column formats. These operations are essential for data analysis and reporting in relational databases.
The PIVOT operation converts rows into columns, creating a cross-tabular format. It's particularly useful for generating summary reports and data aggregations.
SELECT *
FROM (SELECT column1, column2, value FROM source_table)
PIVOT (
aggregate_function(value)
FOR column2 IN (value1, value2, ...)
) AS pivot_table;
Let's consider a table of sales data:
CREATE TABLE sales (
product VARCHAR(50),
quarter VARCHAR(2),
amount INT
);
INSERT INTO sales VALUES
('ProductA', 'Q1', 1000),
('ProductA', 'Q2', 1500),
('ProductB', 'Q1', 2000),
('ProductB', 'Q2', 2500);
To pivot this data and display quarterly sales for each product:
SELECT *
FROM sales
PIVOT (
SUM(amount)
FOR quarter IN ('Q1', 'Q2')
) AS pivot_table;
This query will produce a result with products as rows and quarters as columns.
The UNPIVOT operation is the reverse of PIVOT. It transforms columns into rows, which is useful for normalizing data or preparing it for analysis.
SELECT column1, column_name, column_value
FROM pivot_table
UNPIVOT (
column_value FOR column_name IN (column2, column3, ...)
) AS unpivot_table;
Using the pivoted result from the previous example:
SELECT product, quarter, amount
FROM (
SELECT product, Q1, Q2
FROM pivot_table
) p
UNPIVOT (
amount FOR quarter IN (Q1, Q2)
) AS unpivot_table;
This query will convert the data back to its original row-based format.
To further enhance your understanding of data transformation in SQL, explore these related topics:
Mastering PIVOT and UNPIVOT operations will significantly improve your ability to manipulate and analyze data in SQL, making you more proficient in database concepts and SQL query optimization.