Reputation: 119
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...
Upvotes: 1
Views: 6693
Reputation: 1269493
How about using array
?
select key, array[col1, col2, col3] as cols
from t;
Upvotes: 4
Reputation: 172944
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
Upvotes: 1