You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求编写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;

示例数据查询结果

原语句结果

CountryIDCountryNameAveragePopulation
1India158222339
2USA777605
3PakistanNULL
4United KingdomNULL

优化后语句结果

CountryIDCountryNameAveragePopulation
1India158222339
2USA777605
3Pakistan0
4United Kingdom0

内容的提问来源于stack exchange,提问作者Harshal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 20:40:07