google-bigquery - BigQuery 查询列数不可预测的表

标签 google-bigquery

比方说,我有一个来自日志的表,它看起来像这样: 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 列,但它适用于任何列!)

enter image description here

另一种选择(可能不那么冗长且更易于接受)

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/

相关文章:

google-bigquery - 大查询中的正确案例

google-bigquery - 哪些用户正在访问 BigQuery 表

odbc - 如何通过 ODBC 连接对 BigQuery 进行查询?

python-3.x - 在 python 中模拟 BigQuery 连接

google-bigquery - Big Query 在从一个表插入另一个表时指定 _PARTITIONTIME

python - BigQuery查询限制上下限

javascript - 如何限制 BigQuery 获取的行数?

google-bigquery - 更改 Bigquery 表中字段的数据类型?

sql - 在 BigQuery 中使用所有字符串列的限制

mysql - SQL 到 BigQuery