UNPIVOT
UNPIVOT is a relational operator in SQL that transforms columns into rows. This operator is useful when you have column-oriented data that you want to convert into a row-oriented format, helping in normalizing the denormalized tables.
Example
Output
Explanation
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.
Example
Output
Explanation
In this example, the UNPIVOT
operation is used to transform column data from the ‘orders’ table into rows. Initially, the table contains energy sales for Monday, Tuesday, and Wednesday as separate columns for each order. The UNPIVOT
operation is used to create a new form of the table where each day of the week becomes a separate row linked to the order_id, thus increasing granularity of the data. The ‘Day_of_week’ and ‘Sales’ columns in the resulting table are created by the UNPIVOT
operation.