Skip to main content

Unpivot

SQL Gem

Use the Unpivot Gem to transform your data from a wide format to a long format.

Parameters

ParameterDescription
Column(s) to use as identifiersThe column(s) that will identify to which group or entity the observation corresponds to.
Columns to unpivotThe columns (wide format) that you would like to transform into a single column (long format).
Variable column nameThe name of the column that contains the names of the unpivoted columns. This helps describe the values in the value column.
Value column nameThe name of the column that will contain the values from the unpivoted columns.

Example

Transforming your data into a long format can be beneficial when creating visualizations, comparing variables, handling dynamic data, and more.

Let's think about a time series example. If you have product sales data in a wide format, you may want to transform it into a long format before modeling the time series and analyzing the seasonal patterns in sales.

The image below shows sample input and output tables for this scenario.

Wide and long formats of time series data

This table describes how this transformation was achieved:

ParameterInput
Column(s) to use as identifiersThe Product column is the identifier because it defines which product the sales correspond to.
Columns to unpivotAll of the quarterly sales columns will be unpivoted.
Variable column nameThe variable column is named Quarter because it identifies the sales period.
Value column nameThe value column is named UnitsSold because it contains information about number of units sold.