"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to reconstruct quarterly sales data in BigQuery?

How to reconstruct quarterly sales data in BigQuery?

Posted on 2025-04-13
Browse:787

How to Unpivot Data in BigQuery to Restructure Quarterly Sales Data?

Unpivoting in BigQuery

Question:

How do I restructure a table from having rows of data for different quarters to having columns for the quarters? For example, converting a table like this:

| product | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| Kale | 51 | 23 | 45 | 3 |
| Apple | 77 | 0 | 25 | 2 |

into a table with columns for sales and quarter:

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

Answer:

Update 2021:

BigQuery now includes an UNPIVOT operator that can rotate rows of data into columns.

Before UNPIVOT:

| product | sales | quarter |
|---|---|---|
| Kale | 51 | Q1 |
| Kale | 23 | Q2 |
| Kale | 45 | Q3 |
| Kale | 3 | Q4 |
| Apple | 77 | Q1 |
| Apple | 0 | Q2 |
| Apple | 25 | Q3 |
| Apple | 2 | Q4 |
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3