sql - 在子查询中使用 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);
这会产生所有值中的最小值。但是我对平均值的最小值感兴趣。
请帮助非常感谢您的任何见解。
阿图罗
解决方案
我想你只需要
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
推荐阅读
- javascript - 无法在 Vue 组件的数据属性中调用新日期
- ios - 如何模拟 URLSession?
- opencv - 没有这样的 Gstreamer 工厂:树莓派处理中的 v4l2src 错误
- c# - 启动 Visual Studio MSTest 项目的好方法?
- ios - iOS - 带摘要的网络调用
- r - theme_bw() 从我的 ggplot 中去除所有颜色
- php - 将数据从 mySql DB 加载到 HTML 文本框
- sql - 将字符串转换为日期 SQLSERVER
- c# - 为什么iis使用asp net mvc控制器文件流返回403错误代码
- python - 打开两个 .csv 文件代码 - 一个文件打开另一个不打开