繁体   English   中英

在 BigQuery 中折叠结构数组的元素

[英]Collapse elements of array of structs in BigQuery

我在 BigQuery 中有一组结构,如下所示:

"categories": [
    {
        "value": "A",
        "question": "Q1",
    },
    {
        "value": "B",
        "question": "Q2",
    },
    {
        "value": "C",
        "question": "Q3",
    }
]

我想将值“A”、“B”和“C”折叠到单独的列中,并且该特定行的值应该类似于“A - B - C”。

如何使用 BigQuery 中的查询执行此操作?

考虑下面

select id, 
  ( select string_agg(value, ' - ') 
    from t.questions_struct) values
from questions t   

如果应用于您的问题/答案中的样本数据 -

with questions as (
  SELECT 1 AS id,
    [
        STRUCT("A" as value, "Q1" as question),
        STRUCT("B" as value, "Q2" as question),
        STRUCT("C" as value, "Q3" as question)
    ] AS questions_struct
)
  • output 是

在此处输入图像描述

假设这是一个结构数组,您可以使用:

select (select q.value from unnest(ar) q where q.question = 'q1') as q1,
       (select q.value from unnest(ar) q where q.question = 'q2') as q2,
       (select q.value from unnest(ar) q where q.question = 'q3') as q3
from t;
   

我认为可以使用以下代码完成:

with questions as (
  SELECT 1 AS id,
    [
        STRUCT("A" as value, "Q1" as question),
        STRUCT("B" as value, "Q2" as question),
        STRUCT("C" as value, "Q3" as question)
    ] AS questions_struct
), unnested as (
    select * from questions, unnest(questions_struct) as questions_struct 
) select id, string_agg(value, ' - ') from unnested group by 1  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM