[英]Turn columns into array in BigQuery
I would like to take a table such as this:我想拿一张这样的桌子:
key钥匙 | col1 col1 | col2 col2 | col3 col3 |
---|---|---|---|
"a" “一个” | 0 0 | 2 2 | 3 3 |
"b" “乙” | 1 1 | 1 1 | 3 3 |
"c" “C” | 5 5 | 0 0 | 2 2 |
"d" “d” | 0 0 | 0 0 | 1 1 |
and turn it into this:并将其变成这样:
key钥匙 | col山口 |
---|---|
"a" “一个” | [0, 2, 3] |
"b" “乙” | [1, 1, 3] |
"c" “C” | [5, 0, 2] |
"d" “d” | [0, 0, 1] |
Basically, I want to merge columns into an array.基本上,我想将列合并到一个数组中。 In real life I have 60 columns, all containing integers.在现实生活中,我有 60 列,全部包含整数。 I'll take a struct too if that's easier.如果这更容易,我也会采用结构。 Basically, I don't want to have to deal with 60 column names dynamically.基本上,我不想动态处理 60 个列名。
I can't seem to find an answer for this anywhere, which baffles me - this must be a common use case?我似乎无法在任何地方找到答案,这让我感到困惑 - 这一定是一个常见的用例? It must be late for me...对我来说一定很晚了……
How about using array
?使用array
怎么样?
select key, array[col1, col2, col3] as cols
from t;
Consider below approach考虑以下方法
select key,
(
select array_agg(cast(value as int64))
from unnest(split(trim(format('%t', (select as struct * except(key) from unnest([t]))), '()'))) value
) col
from `project.dataset.table` t
if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.