Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bigquery - How to zip two arrays into one?

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      |
+--------+--------+
like image 971
while Avatar asked Jun 05 '17 09:06

while


People also ask

How do I flatten an array in BigQuery?

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.

How do I Unnest multiple arrays in BigQuery?

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.

What is array AGG in BigQuery?

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.

How do you Unnest an array in BigQuery?

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.


1 Answers

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;
like image 103
Elliott Brossard Avatar answered Sep 24 '22 21:09

Elliott Brossard