How is the “unpivot” function used in Oracle?
In Oracle, UNPIVOT is a operation used to convert columns into rows. It allows you to transform the values of a single column into multiple rows and associate these values with values from other columns.
The basic syntax of the UNPIVOT operation is as follows:
SELECT <columns to keep>,
<unpivot column name>,
<unpivot column value>
FROM <table>
UNPIVOT INCLUDE NULLS
(<unpivot column value>
FOR <unpivot column name>
IN (<column1>, <column2>, ..., <columnN>)
)
Among them:
- “
” are the names of the other columns to be retained. is the newly created column name used to store the names of the original columns. - The column name
is created to store the values from the original column. - The name of the table where the UNPIVOT operation will be performed is
.
- The column names
, , …, are the ones to be unpivoted. Here is an example:
Suppose there is a table named “sales” that includes columns for “product”, “region”, and “Q1”, “Q2”, “Q3”, “Q4” representing the quarterly sales amount for different products in different regions. You can use the UNPIVOT operation to transform these columns into a more easily analyzeable form.
SELECT product, region, quarter, sales FROM sales UNPIVOT INCLUDE NULLS (sales FOR quarter IN (Q1, Q2, Q3, Q4) )
This query will produce a result set where each row represents quarterly sales figures for a product in a specific region.
It is important to note that the UNPIVOT operation is commonly used for analyzing and creating reports, as well as converting data when columns need to be transformed into rows.
- The column names