【问题标题】:Generating JSON on the fly with BigQuery使用 BigQuery 即时生成 JSON
【发布时间】:2021-06-26 02:45:59
【问题描述】:

BigQuery 有一个 TO_JSON_STRING() 函数,可将 SQL 表达式的结果转换为 json 字符串。我试图弄清楚如何将它与具有 嵌套数组 的数据结构一起使用,该结构在 BigQuery 的表中表示为 一对多 关系。

这是我要运行的查询:

SELECT a.account_id, 
  TO_JSON_STRING((SELECT s.skill_id FROM skills s WHERE s.account_id = a.account_id))
FROM accounts a

我从 BigQuery 收到此错误

标量子查询产生了多个元素

最终目标是将account_id 也放入 json 中,并保留在字符串列中。

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    这是另一种解决方案;

    with accounts as (
      select *
        from unnest([struct(1 as account_id, 'first acc' as account_name)
                    ,struct(2 as account_id, 'second acc' as account_name)
                    ,struct(3 as account_id, 'third acc' as account_name)
                    ])
    )
    , skills as (
      select *
        from unnest([struct(1 as account_id, 1 as skill_id)
                    ,struct(1 as account_id, 2 as skill_id)
                    ,struct(1 as account_id, 3 as skill_id)
                    ,struct(2 as account_id, 1 as skill_id)
                    ,struct(2 as account_id, 4 as skill_id)
                    ])
    )
    , nest as (
      select a.account_id
            ,any_value(a.account_name) as account_name
            ,to_json_string(ifnull(array_agg(s.skill_id ignore nulls),[])) as skills
      from accounts a
      left join skills s
      on a.account_id = s.account_id
      group by a.account_id
    )
    select *
    from nest
    

    输出将如下所示:

    【讨论】:

    • 美丽。你能包括如何在json中添加account_name吗?
    • 您能否尝试在 SQL 的最后一个部分将 * 替换为 to_json_string(nest)然后先删除to_json_string
    • 可以,但是上面的to_json_string必须删除。
    • 另一种方法是将答案中的那个替换为to_json_string(struct(a.account_id as account, ifnull(array_agg(s.skill_id ignore nulls),[]) as skills))
    【解决方案2】:

    你可以先加入,然后生成json,像这样:

    select TO_JSON_STRING(t) from (select account.account_id as acc_id, skills.* from account inner join skills using(account_id)) as t
    

    【讨论】:

    • 一个账号可以拥有多个技能,我希望每个账号一个json。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多