在子查询中使用 min() 和 avg()

use min() and avg () in subquery

我正在使用来自 ibm 云的 db2 和 sql。 我的数据包含 1 table 个 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);

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

请帮忙 非常感谢任何见解。

阿图罗

你可以试试下面的-

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

现在.. 出于性能原因我不推荐这样做,但是如果你真的真的想避免使用 limitorder by 并且也不想使用 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