[英]row values to column and columns names to values bigquery
i'm trying to create a new table that has two columns 'tags' ,'cnt'我正在尝试创建一个包含两列“标签”、“cnt”的新表
'tags' will contain the columns names as values 'tags' 将包含列名称作为值
'cnt' contain the value per origin column 'cnt' 包含每个原点列的值
You can unpivot using arrays:您可以使用数组取消旋转:
select el.which, el.cnt
from t cross join
(unnest([struct('ALL_CLOSE' as which, t.all_close as cnt),
struct('ALL_OPEN' as which, t.all_open as cnt),
. . .
])) u(el)
Below for BigQuery Standard SQL下面是 BigQuery 标准 SQL
#standardSQL
SELECT
TRIM(SPLIT(kv, ':')[OFFSET(0)], '"') tag,
SPLIT(kv, ':')[SAFE_OFFSET(1)] cnt
FROM `project.dataset.table` t,
UNNEST(REGEXP_EXTRACT_ALL(TRIM(TO_JSON_STRING(t), '{}'), r'(.*?)(?:,|$)')) kv
You can test, play with above using sample data from your question as in below example您可以使用您的问题中的示例数据进行测试,使用上面的示例数据,如下例所示
#standardSQL
WITH `project.dataset.table` AS (
SELECT 8279 all_close, 4 all_open, 1504 only_o, 16785 only_f
)
SELECT
TRIM(SPLIT(kv, ':')[OFFSET(0)], '"') tag,
SPLIT(kv, ':')[SAFE_OFFSET(1)] cnt
FROM `project.dataset.table` t,
UNNEST(REGEXP_EXTRACT_ALL(TRIM(TO_JSON_STRING(t), '{}'), r'(.*?)(?:,|$)')) kv
with result结果
Row tag cnt
1 all_close 8279
2 all_open 4
3 only_o 1504
4 only_f 16785
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.