If I have two arrays in BigQuery that I know are of equal size. How can i zip them into one array of structs or an array of two element arrays or similar?
The following query gives me all possible combinations of x and y which is not what I want.
WITH test AS (
SELECT
['a', 'b', 'c'] as xs,
[1, 2, 3] as ys
)
SELECT struct(x, y) as pairs
FROM test, unnest(xs) as x, unnest(ys) as y
I would like to get something like this:
+--------+--------+
| pair.x | pair.y |
+--------+--------+
| a | 1 |
| b | 2 |
| c | 3 |
+--------+--------+
To flatten an entire column of ARRAY s while preserving the values of the other columns in each row, use a correlated cross join to join the table containing the ARRAY column to the UNNEST output of that ARRAY column.
Can We Unnest Multiple Arrays? When we use the UNNEST function on a column in BigQuery, all the rows under that column is flattened all at once. Currently, the UNNEST function does not accept multiple arrays as parameters. We need to merge the arrays into a single array before flattening it.
ARRAY_AGG. Returns an ARRAY of expression values. To learn more about the optional arguments in this function and how to use them, see Aggregate function calls. To learn more about the OVER clause and how to use it, see Window function calls.
You can do this with a CROSS JOIN. A cross join will take every individual element of your unnested array and join it back to its parent row. This will create multiple rows for each element of your array but you can then filter it down.
Use WITH OFFSET
and the bracket operator:
WITH test AS (
SELECT
['a', 'b', 'c'] as xs,
[1, 2, 3] as ys
)
SELECT struct(x, ys[OFFSET(off)] as y) as pairs
FROM test, unnest(xs) as x WITH OFFSET off;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With