简体   繁体   English

在 BigQuery 中将列转换为值

[英]Turn columns into values in BigQuery

I have the following data:我有以下数据:

     date_ country category_A category_B
2022-12-11     USA        100        200
2022-12-11  Canada       2000        400

which is generated by this query:这是由此查询生成的:

select
  date('2022-12-11') as date_, 'USA' as country, 100 as category_A, 200 as category_B,
union all select 
  date('2022-12-11') as date_, 'Canada' as country, 2000 as category_A, 400 as category_B

What I would like to do is to turn only the last two columns of the data into values and get a single column for the values, like this table:我想做的是只将数据的最后两列转换为值,并为值获取一个列,如下表:

     date_ country   category  value 
2022-12-11     USA category_A    100       
2022-12-11     USA category_B    200        
2022-12-11  Canada category_A   2000   
2022-12-11  Canada category_B    400   

Maybe it's not perfect but you can use the following query:也许它并不完美,但您可以使用以下查询:

with countries AS
(select
  date('2022-12-11') as date_, 'USA' as country, 100 as category_A, 200 as category_B,
union all select 
  date('2022-12-11') as date_, 'Canada' as country, 2000 as category_A, 400 as category_B
)

select 
  date_,
  country,
  category
from countries,
unnest(array[struct('category_A' AS category_name, category_A AS category_value), struct('category_B' AS category_name, category_B AS category_value)]) as category;

The result is:结果是:

在此处输入图像描述

In the unnest , you need to add all the expected category columns.unnest中,您需要添加所有预期的类别列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM