Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigQuery: Create a table from arrays

I want to create a table with two columns from two different arrays.

Array1: [1,2,3]

Array2: [11,12,13]

Required Table:

two columns, 3 rows

By using this query, I got 1 row

SELECT 
[1,2,3] AS S1,
[11,12,13] AS S2

1 row, 2 columns

I tried UNNEST, but got cartesian product

SELECT S1, S2
FROM 
UNNEST([1,2,3]) AS S1,
UNNEST([11,12,13]) AS S2

2 columns, 9 rows - cartesian product

How can I create required table (pic 1) from arrays?

Thanks

like image 362
john Avatar asked Feb 07 '26 19:02

john


1 Answers

One method uses a join and WITH OFFSET:

SELECT S1, S2, o1, o2
FROM UNNEST([1, 2, 3]) s1 WITH OFFSET o1 LEFT JOIN
     UNNEST([11, 12, 13]) S2 WITH OFFSET o2
     ON o1 = o2;

It would be nice if UNNEST() in BigQuery supported multiple arguments, as some other databases do.

like image 172
Gordon Linoff Avatar answered Feb 09 '26 12:02

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!