Not sure what functions to call, but transpose is the closest thing I can think of.
I have a table in BigQuery that is configured like this:

but I want to query a table that is configured like this:

What does the SQL code look like for creating this table?
Thanks!
Use the UNION of tables (with ',' in BigQuery), plus some column aliasing:
SELECT Location, Size, Quantity
FROM (
SELECT Location, 'Small' as Size, Small as Quantity FROM [table]
), (
SELECT Location, 'Medium' as Size, Medium as Quantity FROM [table]
), (
SELECT Location, 'Large' as Size, Large as Quantity FROM [table]
)
@Felipe, I tried this using standard-sql but I get an error on the first line of your query that says: "Column name Location is ambiguous at [1:8]"
I've used an alternate query that works for me:
SELECT Location, 'Small' as Size, Small as Quantity FROM `table`
UNION ALL
SELECT Location, 'Medium' as Size, Medium as Quantity FROM `table`
UNION ALL
SELECT Location, 'Large' as Size, Large as Quantity FROM `table`
I have a solution that uses STRUCT
s, ARRAY
s and CROSS JOIN
+ UNNEST
:
WITH
My_Table_Metrics_Data AS (
SELECT
...,
[
STRUCT('...' AS Metric, ... AS Data),
STRUCT('...' AS Metric, ... AS Data),
] AS Metrics_Data
FROM
`My_Dataset.My_Table`
WHERE
...
)
SELECT
...,
Metric_Data
FROM
My_Table_Metrics_Data
CROSS JOIN
UNNEST(My_Table_Metrics_Data.Metrics_Data) AS Metric_Data
Full explanation and instructions: https://yuhuisdatascienceblog.blogspot.com/2018/06/how-to-unpivot-table-in-bigquery.html
来源:https://stackoverflow.com/questions/27832170/how-to-unpivot-in-bigquery