在子查询中使用min和avg

问题描述

我正在从ibm云和sql开发db2。 我的数据包含一个包含3列的表格:学校,其总体表现(水平)和位置。 我想使用具有平均值和最小值的子查询来找到平均级别最低的位置。

我有执行此工作的这段代码

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);

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

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

Arturo

解决方法

您可以尝试以下-

with cte as
(
select location,avg(safety_score) as safety_score  from chicago_public_schools group by location
)
select community_area_name
from chicago_public_schools
where safety_score = (select min(safety_score) from cte)
,

我认为您只需要

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 bylimit一起使用,并且也不想使用cte ,您可以使用window 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