另一个选项 - 不需要知道列名,因此无论有多少列及其名称,都可以使用相同的查询
select id,
( select as struct split(kv, ':')[offset(0)] col,
cast(split(kv, ':')[offset(1)] as numeric) value
from t.kvs as kv
order by value desc
limit 1
).*
from(
select *,
split(translate(to_json_string((select as struct * except(id) from unnest([t]))), '{}"', '')) kvs
from `project.dataset.table` t
) t
您可以使用虚拟数据进行测试,如下例所示
with `project.dataset.table` as (
select 1 id, 11 col1, 12 col2, 13 col3, 14 col4 union all
select 2, 24, 23, 22, 21 union all
select 3, 31, 34, 32, 33
)
select id,
( select as struct split(kv, ':')[offset(0)] col,
cast(split(kv, ':')[offset(1)] as numeric) value
from t.kvs as kv
order by value desc
limit 1
).*
from(
select *,
split(translate(to_json_string((select as struct * except(id) from unnest([t]))), '{}"', '')) kvs
from `project.dataset.table` t
) t
有输出