[英]Update BigQuery repeated record field with condition
I have a BigQuery
table named 'events' with below structure:我有一个名为“事件”的
BigQuery
表,其结构如下:
My goal is to update all rows where country is US and replace it with 'United States', and where country is CH to replace it with 'China'.我的目标是更新所有国家/地区为美国的行,并将其替换为“美国”,以及国家/地区为 CH 的所有行,以将其替换为“中国”。
I tried to look at other questions where they update repeated record but I didn't find anything specific to what I want and didn't quite understood the method.我试图查看他们更新重复记录的其他问题,但我没有找到任何特定于我想要的东西并且不太理解该方法。 (for example this StackOverflow question )
(例如这个 StackOverflow 问题)
Any help would be much appreciated.任何帮助将非常感激。
If you're trying to modify only two country codes into country names, following would be one of possible approach.如果您只想将两个国家/地区代码修改为国家/地区名称,则以下是一种可能的方法。
Note - below query is assuming that country code and region code can conflict each other.注意- 下面的查询假设国家代码和区域代码可以相互冲突。
UPDATE sample
SET attributes = ARRAY (
SELECT AS STRUCT a.name, IFNULL(c.name, a.value)
FROM UNNEST(attributes) a
LEFT JOIN UNNEST([
STRUCT('US' AS code, 'United States' AS name), ('CH', 'China')
]) c ON a = ('country', c.code)
)
WHERE ('country', 'US') IN UNNEST(attributes)
OR ('country', 'CH') IN UNNEST(attributes)
;
More general approach would be using a mapping table.更通用的方法是使用映射表。
DECLARE countries ARRAY<STRUCT<code STRING, name STRING>> DEFAULT [
('US', 'United States'),
('CH', 'China') --, you can add more mappings of country code and it's name.
];
With the above mapping table, below query will generate same result as first query.使用上面的映射表,下面的查询将生成与第一个查询相同的结果。
UPDATE sample
SET attributes = ARRAY(
SELECT AS STRUCT a.name, IFNULL(c.name, a.value)
FROM UNNEST(attributes) a
LEFT JOIN UNNEST(countries) c ON a = ('country', c.code)
)
WHERE TRUE
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.