Unpivot using SQL
When converting columns into rows in SQL, unpivoting is used, effectively converting wide format (i.e., data with many columns) into long format (i.e., data with fewer columns and more rows). The process of pivoting, which includes turning rows into columns, is the opposite of this.
Here is the syntax of Unpivot in SQL:
SELECT [column1], [column2], [column3]
FROM (
SELECT [id], [column1], [column2], [column3]
FROM [table_name]
) AS [source_table]
UNPIVOT (
[value] FOR [column_name] IN ([column1], [column2], [column3])
) AS [unpivot_table];
In this syntax:
[column1]
, [column2]
, and [column3]
are the columns you want to unpivot.[table_name]
is the name of the table containing the data you want to unpivot.[id]
is a column that uniquely identifies each row in the table.[value]
is the name of the column that will contain the values that were previously in the unpivoted columns.[column_name]
is the name of the column that will contain the original column names.[unpivot_table]
is the name of the table that will contain the unpivoted data.
Here is an example of unpivot operation in SQL using the UNPIVOT keyword:
SELECT * FROM ( SELECT id, col1, col2, col3 FROM test_table ) AS t UNPIVOT ( value FOR column_name IN (col1, col2, col3) ) AS u;
sales
with the columns id, year, sales_Q1, sales_Q2, sales_Q3, sales_Q4.sales
, use the following SQL query:In the above example, the sales_Q1, sales_Q2, sales_Q3 and sales_Q4 columns have been unpivoted into a single sales
column, with a new sales_quarter
column indicating which quarter the sales value belongs to.
Comments
Post a Comment