The pivot operation works much the same as the SQL concept: "rotating" and expanding single columns of values into multiple columns (one for each value), creating a wider but shorter table. It is nearly the opposite of the unpivot operation, though it will merge duplicates and drop null values, which unpivot cannot undo. You can perform pivot operations using the pivot and pivot_values parameters in the options map of /aggregate/groupby or via the SQL PIVOT function. Visit the Aggregation documentation to review details on aggregating data.
A pivot operation could be used to convert a table like this:
|
|
into a table like this:
|
|
Each phone type in the pivoted key column becomes a prefix of one of the resulting value columns of the pivot, with the suffix for those columns (Phone) specified by the user.
The results of a pivot may be written to a separate memory-only table using the result_table option. This table can be persisted (like normal tables) using the result_table_persist option.
A memory-only table name must adhere to the standard naming criteria. Each memory-only table exists within a schema and follows the standard name resolution rules for tables.
Examples
Customer Phone Numbers
Given a source table phone_list, which lists each phone number for a customer as a separate record in the table:
|
|
A pivot operation can be performed in Python like so, creating a single record per customer with the home, work, & cell phone numbers as separate columns:
|
|
The resulting table looks like this:
|
|
Student Grades
Given a source table qtr_grade, which lists each student's quarterly grade as a separate record in the table:
|
|
Performing a pivot operation in Python on the table converts it into a table with one record per student with each quarter grade as a separate column:
|
|
The resulting table looks like this:
|
|
Limitations
- Pivot values are case sensitive; e.g., a value of Home will not match records with values of HOME or home, and it will generate a new column with Home as the name (or part of the name if an alias was specified).
- Pivot values cannot contain commas, making the operation generally inapplicable to data containing them, like JSON, vector, and comma-embedded strings.
- When the result_table option is used, pivot values must meet standard column naming criteria, as they will be used to construct the output table column names. This may prevent the direct pivoting of some data types, like date & UUID (among others), that naturally contain invalid column naming characters.
- As the pivot operation is executed via /aggregate/groupby, all Aggregation Limitations also apply.