SQL 查询从聚合平均值中查找最大行
假设我有以下表格:
Sailor(sid, sname, age)
Boat(bid, sid)
每艘船可以有很多水手,每个水手可以在很多船上服务。我想做的是找到水手平均年龄最高的船。
我可以使用这个子查询找到每艘船上水手的平均年龄:
SELECT b.bid, AVG(s.age) AS avg_age FROM sailor s, boat b
WHERE b.sid = s.sid
GROUP BY b.bid
但是,我陷入了如何进一步从这个子查询中找到最大行的问题。
PS 我也在寻找与 MySQL 兼容的查询,如果这有什么区别的话。
Supposed I have the following tables:
Sailor(sid, sname, age)
Boat(bid, sid)
Each boat can have many sailors, and each individual sailor can serve on many boats. What I want to do is to find the boat with the highest average age of sailors.
I can find the average age of the sailor on each boat with this subquery:
SELECT b.bid, AVG(s.age) AS avg_age FROM sailor s, boat b
WHERE b.sid = s.sid
GROUP BY b.bid
However, I am stuck on how to find the maximum row from this subquery further on.
P.S. I'm also looking for MySQL-compatible query, if that makes any difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将返回一行,并且由于排序,它将包含最大平均年龄。
This will return one row, and because of the ordering it will contain the maximum average age.
在sql server中,它会是:
我不熟悉MySQL,但是有一个Linmit关键字可以“限制”返回的行数,如果您使用它而不是Top 1,它应该可以工作,不是吗?我不太确定语法,但是......
In sql server it would be:
I'm not up on MySQL, but there's a Linmit keyword that "limits" the enumber of rows returned, If you use that instead of the Top 1, it should work, no? I'm not exactly sure of the syntax, but ...