首页 > 解决方案 > 在同一个表中合并 SQL 查询

问题描述

我正在尝试结合以下查询:

SELECT country_name, 
       avg(value) as Entrance_Age 
FROM `bigquery-public-data.world_bank_intl_education.international_education` 
WHERE indicator_code = 'UIS.THAGE.0' 
GROUP BY country_name
ORDER BY avg(value) DESC LIMIT 10

SELECT avg(value) as Illiterate
FROM `bigquery-public-data.world_bank_intl_education.international_education`
WHERE indicator_code = 'UIS.ILLPOP.AG25T64'
GROUP BY country_name
ORDER BY avg(value) DESC LIMIT 10

第一个查询的输出是:[1]: https://i.stack.imgur.com/jsxx7.png

目标是在 Entrance_Age 旁边获得另一个名为“Illiterate”的列。我试图在入学年龄列旁边显示这 10 个国家中每个国家的文盲率。所有数据都来自同一张表。这些值与指标代码相关联,指标代码是基于指标代码的统计信息。

我尝试了多个连接,但似乎无法获得一个有效的连接。

如果我的问题有什么遗漏,请告诉我。

标签: sqljoingoogle-bigquery

解决方案


您可以使用条件聚合:

SELECT country_name, 
       avg(case when indicator_code = 'UIS.THAGE.0' then value end) as Entrance_Age,
       avg(case when indicator_code = 'UIS.ILLPOP.AG25T64' then value end) as illiterate 
FROM `bigquery-public-data.world_bank_intl_education.international_education` 
GROUP BY country_name
ORDER BY Entrance_Age DESC LIMIT 10

推荐阅读