问题描述
我有一个包含多个类似列的数据源,看起来像这样,每个问题作为一个新列和相应的响应: Original
我想将它转换为使用具有两个成对列的数组,这样它最终看起来像这样,只有两列,问题和响应,并且每个遗留列只有自己的键(1,2,3 等): Desired
请耐心等待,我确定这很简单,我认为需要使用 array_agg 甚至可能是 unpivot,但我已经浏览了过去的帖子,但找不到任何具有类似解决方案的价值与来自“平面”源的多列名称相关的问题列/根据原始列名称在新字段中分配值。
我有这个,但我需要得到问题/响应配对....
select ID,array_agg(response ignore nulls) Questionnaire
from datasourcename,unnest([Q1Response,Q2Response,]) response
group by ID
非常感谢任何支持(第一次发布!)
解决方法
试试这个:
with mytable as (
select 1 as id,'a' as q1response,'c' as q2response,'a' as q3response,'d' as q4response union all
select 2,'b','a','d' union all
select 3,'a'
)
select
id,[ struct('1' as question,q1response as response),struct('2' as question,q2response as response),struct('3' as question,q3response as response),struct('4' as question,q4response as response)
] as q
from mytable
,
考虑以下解决方案 - 它适用于表格中任意数量的问题/列,无需更改代码
select id,array(
select as struct regexp_extract(kv[offset(0)],r'\d+') as Question,kv[offset(1)] as Response
from unnest(regexp_extract_all(to_json_string(t),r',("[^"]+":"[^"]*")')) kvs,unnest([struct(split(trim(kvs,'"'),'":"') as kv)])
) Questionnaire
from `project.dataset.table` t
如果应用于您问题中的样本数据 - 输出为