Home >Database >Mysql Tutorial >How to Unpivot a Table in BigQuery Using SQL?

How to Unpivot a Table in BigQuery Using SQL?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 04:34:09484browse

How to Unpivot a Table in BigQuery Using SQL?

SQL Query for Unpivoting a Table in BigQuery

In BigQuery, unpivoting involves transforming a table with rows of multiple values into a table with single values in separate columns. To achieve this in the context of this query, where you desire to transpose the Q1, Q2, Q3, and Q4 columns into a sales and quarter format, you can leverage the power of the UNPIVOT operator.

The updated SQL code for your query, utilizing the UNPIVOT operator, is outlined below:

SELECT product,
       quarter,
       sales
FROM UNPIVOT(
  your_table_name
)
AS UNPIVOTED
ORDER BY sales DESC;

This SQL query will effectively "unpivot" your table, rotating the Q1, Q2, Q3, and Q4 columns into separate sales and quarter columns. The result will be a table structured as follows:

product quarter sales
Kale Q1 51
Kale Q2 23
Kale Q3 45
Kale Q4 3
Apple Q1 77
Apple Q2 0
Apple Q3 25
Apple Q4 2

This unpivoted table provides a more straightforward and concise representation of your data, making it easier to query and analyze the sales performance for each product across different quarters.

The above is the detailed content of How to Unpivot a Table in BigQuery Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn