简体   繁体   中英

Turn columns into array in BigQuery

I would like to take a table such as this:

key col1 col2 col3
"a" 0 2 3
"b" 1 1 3
"c" 5 0 2
"d" 0 0 1

and turn it into this:

key col
"a" [0, 2, 3]
"b" [1, 1, 3]
"c" [5, 0, 2]
"d" [0, 0, 1]

Basically, I want to merge columns into an array. In real life I have 60 columns, all containing integers. I'll take a struct too if that's easier. Basically, I don't want to have to deal with 60 column names dynamically.

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 ?

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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