BigQuery's latest addition, the PIVOT function, has garnered considerable attention for its ability to transform data into a more pivot-table-like format. However, when faced with scenarios where the pivot column values are not known in advance, conventional methods may prove ineffective.
In such cases, a dynamic approach using string concatenation can bypass this limitation. By dynamically generating the pivot query based on the distinct values of the quarter column, we can effectively handle any number of unknown pivot values.
The following code snippet exemplifies this dynamic approach:
execute immediate ( select '''select * from (select * from `project.dataset.Produce`) pivot(sum(sales) for quarter in ("''' || string_agg(quarter, '", "') || '''")) ''' from (select distinct quarter from `project.dataset.Produce` order by quarter) );
Query Generation:
Subquery:
This dynamic approach offers several benefits:
The above is the detailed content of How Can I Dynamically Pivot Data in BigQuery When Pivot Column Values Are Unknown?. For more information, please follow other related articles on the PHP Chinese website!