请求编写Grid DB查询:按国家计算并取整平均人口(降序)
Grid DB 查询实现:计算各国平均人口并排序
需求实现查询语句
SELECT c.CountryID, c.CountryName, ROUND(AVG(s.Population), 0) AS AveragePopulation FROM Country c LEFT JOIN State s ON c.CountryID = s.CountryID GROUP BY c.CountryID, c.CountryName ORDER BY AveragePopulation DESC;
关键说明
- 表关联:使用
LEFT JOIN保证所有国家(即使没有对应州数据)都能出现在结果中 - 四舍五入处理:用
ROUND(AVG(s.Population), 0)替代FLOOR,实现将平均人口四舍五入到最近整数 - 分组与排序:按
CountryID和CountryName分组计算平均值,最终按AveragePopulation降序排列
可选优化:处理无州数据的国家
如果希望没有州数据的国家平均人口显示为0而非NULL,可以用COALESCE函数处理:
SELECT c.CountryID, c.CountryName, ROUND(COALESCE(AVG(s.Population), 0), 0) AS AveragePopulation FROM Country c LEFT JOIN State s ON c.CountryID = s.CountryID GROUP BY c.CountryID, c.CountryName ORDER BY AveragePopulation DESC;
示例数据查询结果
原语句结果
| CountryID | CountryName | AveragePopulation |
|---|---|---|
| 1 | India | 158222339 |
| 2 | USA | 777605 |
| 3 | Pakistan | NULL |
| 4 | United Kingdom | NULL |
优化后语句结果
| CountryID | CountryName | AveragePopulation |
|---|---|---|
| 1 | India | 158222339 |
| 2 | USA | 777605 |
| 3 | Pakistan | 0 |
| 4 | United Kingdom | 0 |
内容的提问来源于stack exchange,提问作者Harshal
相关产品推荐
相关产品推荐

