比方说,我有一个来自日志的表,它看起来像这样: Log Table
我需要一个像这样的结果表: Result table
但问题是我的数据集不仅有 7 个,而且可能有 24 个、100 个值列。 我的 7 个值列的查询是:
select
*
from My_Dataset
unpivot
(status for value in (value_1, value_2, value_3, value_4, value_5, value_6, value_7))```
But is there anyway to automatic this process for value_n?
Thank you.
最佳答案
考虑以下方法
select id, arr[offset(1)] as value
from your_table t,
unnest(split(translate(to_json_string(t), '{}"', ''))) kv,
unnest([struct(split(kv, ':') as arr)])
where starts_with(arr[offset(0)], 'value_')
如果应用于您问题中的示例数据(我只使用了三个 value_N 列,但它适用于任何列!)
另一种选择(可能不那么冗长且更易于接受)
select id, val
from your_table t, unnest([to_json_string(t)]) json,
unnest(`bqutil.fn.json_extract_keys`(json)) col with offset
join unnest(`bqutil.fn.json_extract_values`(json)) val with offset
using(offset)
where starts_with(col, 'value_')
显然与上面第一个选项的输出相同
关于google-bigquery - BigQuery 查询列数不可预测的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70874185/