BigQuery: How to extract only certain field from REPEATED records as another REPEATED field

1483 views google-bigquery
4

Here is an example table in BigQuery:

WITH test AS (
  SELECT
    [ 
      STRUCT("Rudisha" as name, 123 as id),
      STRUCT("Murphy" as name, 124 as id),
      STRUCT("Bosse" as name, 125 as id),
      STRUCT("Rotich" as name,  126 as id)
    ] AS data

    UNION

    [
      STRUCT("Lewandowski" as name, 127 as id),
      STRUCT("Kipketer" as name, 128 as id),
      STRUCT("Berian" as name, 129 as id)
    ] AS data
)

Here I want to extract 'id' fields in the record field ('data') as a repeatable field. So the number of rows will remain the same but only with ids field which is of repeated type:

ids: [123, 124, 125, 126]
ids: [127, 128, 129]

How can I do this? Thanks!

answered question

1 Answer

5

Below is for BigQuery Standard SQL

#standardSQL
WITH test AS (
  SELECT
    [ 
      STRUCT("Rudisha" AS name, 123 AS id),
      STRUCT("Murphy" AS name, 124 AS id),
      STRUCT("Bosse" AS name, 125 AS id),
      STRUCT("Rotich" AS name,  126 AS id)
    ] AS data
    UNION ALL SELECT
    [
      STRUCT("Lewandowski" AS name, 127 AS id),
      STRUCT("Kipketer" AS name, 128 AS id),
      STRUCT("Berian" AS name, 129 AS id)
    ] AS data
)
SELECT ARRAY(SELECT id FROM UNNEST(data)) ids
FROM test

posted this

Have an answer?

JD

Please login first before posting an answer.