BigQuery-使用标准SQL汇总行

问题描述 投票:0回答:1

考虑此表

+------------+----------------+-------------+
|    date    |   region_name  |  population |
+------------+----------------+-------------+
| 2000-02-11 | Lower Normandy |   1.000.000 |
+------------+----------------+-------------+
| 2000-02-11 | Upper Normandy |   1.100.000 |
+------------+----------------+-------------+
| 2020-04-25 | Lower Normandy |   1.800.000 |
+------------+----------------+-------------+
| 2020-04-25 | Upper Normandy |   1.900.000 |
+------------+----------------+-------------+

我想将Lower NormandyUpper Normandy的行汇总为Normandy,并根据date列将population相加。

预期结果将是:

+------------+----------------+-------------+
|    date    |   region_name  |  population |
+------------+----------------+-------------+
| 2000-02-11 |       Normandy |   2.100.000 |
+------------+----------------+-------------+
| 2020-04-25 |       Normandy |   3.700.000 |
+------------+----------------+-------------+

此聚合的结果将用于创建新视图。

如何使用标准SQL在BigQuery中完成?

sql google-bigquery sql-merge nosql-aggregation
1个回答
0
投票

您可以使用case表达式来更改名称:

select date,
       (case when region_name like '%Normandy' then 'Normandy' else region_name end) as region_name,
       sum(population) as population
from t
group by 1, 2;

此匹配以“ Normandy”结尾的任何内容。当然,您可以使用region_name in ('Upper Normandy', 'Lower Normany')来提高精度(并增加键入)。

或者,如果您只关心这四行,则只需分配region_name

select date, 'Normandy' as region_name, sum(population) as population
from t
where region_name like '%Normandy'
group by date;
© www.soinside.com 2019 - 2024. All rights reserved.