0

I'm trying to flatten arrays in different columns with different lengths without duplicating the results.

For example (using standard SQL):

WITH
  x AS (
  SELECT
    ARRAY[1,
    2,
    3] AS a,
    ARRAY[1,
    2] AS b)
SELECT
  a,
  b
FROM
  x,
  x.a,
  x.b

Produces:

+-----++-----+
| a   |   b  |
+-----++-----+
|   1 |   1  |
|   1 |   2  |
|   2 |   1  |
|   2 |   2  |
|   3 |   1  |
|   3 |   2  |
+-----++-----+

It should look like this:

+-----++-----+
| a   |   b  |
+-----++-----+
|   1 |   1  |
|   2 |   2  |
|   3 | null |
+-----++-----+
9
  • MySQL <> google-bigquery.. Commented Jun 13, 2019 at 15:54
  • Looks like you are missing group by to get desired results Commented Jun 13, 2019 at 15:54
  • @TamirKlein - Could you provide an example? Commented Jun 13, 2019 at 15:55
  • 1
    @RaymondNijland - cross join produces the same result. Could you provide an example to illustrate your point? Commented Jun 13, 2019 at 15:58
  • 1
    @RaymondNijland - The example is in the question. Please paste the SQL into BigQuery and hit run to reproduce the example in the question. Commented Jun 13, 2019 at 16:07

1 Answer 1

2

You can use JOIN:

SELECT a, b
FROM x LEFT JOIN
     UNNEST(x.a) a left join
     unnest(x.b) b 
     ON a = b;
Sign up to request clarification or add additional context in comments.

3 Comments

This works really well. How would you add more columns beyond "a" and "b"? Let's say you had 2 more nested columns. How would you do your join? Initially, an "and" statement made sense ("... a = b and b = c") but it just duplicated "a" and "b". Any thoughts?
@ethanenglish . . . You can keep adding additional unnest()s. If you cannot get it to work, you should ask another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.