我正在尝试编写一个返回Hobby名称的查询,其中包含该业余爱好者的年龄平均值。
我可以获得年龄最小的平均爱好,但我无法获得业余爱好的Name属性。 这就是我获得最低年龄的方式:
SELECT MIN(avg)
FROM (
SELECT AVG(age) as avg
FROM Hobby H NATURAL JOIN Person P NATURAL JOIN Hobbies R
GROUP BY (R.hnum))
表格是:
Hobby (hnum, hname)
Person (pid, pname, age)
Hobbies (pid, hnum, frequency)
通常我会想让这个块成为一个内部块然后比较每个爱好的最小年龄,但因为爱好没有最小年龄属性我不能这样做。
我已经更新了ErsinGülbahar对此的建议:
SELECT MIN(avg), name
FROM (
SELECT AVG(age) as avg, min(hname) name
FROM Hobby H NATURAL JOIN Person P NATURAL JOIN Hobbies R
GROUP BY (R.hnum))
但唯一的问题是,如果有两个具有相同最小平均年龄的爱好,则此查询仅返回一行。 有什么建议吗?
答案 0 :(得分:1)
SELECT MIN(avg), min(name)
FROM (
SELECT AVG(age) as avg, min(hname) name
FROM Hobby H NATURAL JOIN Person P NATURAL JOIN Hobbies R
GROUP BY (R.hnum))
答案 1 :(得分:0)
您还可以使用TOP 1和ORDER BY:
SELECT TOP 1 (R.hnum), (R.hname), AVG(age)
FROM Hobby H NATURAL JOIN Person P NATURAL JOIN Hobbies R
GROUP BY (R.hnum), (R.hname)
ORDER BY AVG(age)