首页 > 解决方案 > 在子查询中使用 min() 和 avg()

问题描述

我正在研究 ibm cloud 和 sql 的 db2。我的数据包含 1 个包含 3 列的表:学校、它们的整体表现(水平)和位置。我想使用带有 avg 和 min 的子查询找到具有最低 AVERAGE 级别的位置。

我有这段代码可以完成这项工作:

select location, avg(level) as avglevel
from schools_table
group by location
order by avglvl
limit 1;

但我正在寻找更像:

select location
from schools_table
where level = (select min(level) from schools_table);

这会产生所有值中的最小值。但是我对平均值的最小值感兴趣。

请帮助非常感谢您的任何见解。

阿图罗

标签: sqldb2subqueryaveragemin

解决方案


我想你只需要

select community_area_name
from chicago_public_schools
where safety_score = (select avg(safety_score)
                      from chicago_public_schools 
                      group by location
                      order by avg(safety_score) asc --sort the result
                      limit 1); --pick the smallest avg

现在..出于性能原因,我不建议这样做,但是如果您真的想避免order by使用limit并且也不想使用 a cte,则可以使用 awindow function

select community_area_name
from chicago_public_schools
where safety_score = (select distinct min(avg(safety_score)) over()
                      from chicago_public_schools 
                      group by location)

如果你也想避免window functions,你可以完全依赖子查询,但是——太丑了

select community_area_name
from chicago_public_schools a
join (select min(safety_score) as min_safety_score
      from (select avg(safety_score) as safety_score  
            from chicago_public_schools 
            group by location) b) c on a.safety_score = c.min_safety_score

推荐阅读