使用平均值的查询有什么问题?

时间:2012-07-03 14:40:03

标签: mysql sql

课程(cid,cname,description)

教授(pid,pname)

教学(tid,cid,pid,year,semester,department)

学生(sid,lname,fname,b_date,department)

Enrolled_stud(sid,tid,enrollment_date,grade,grade_date)

问题:查询平均分最高的所有学生姓名:

SELECT a.sname,a.avg
FROM (SELECT s1.sname,avg(e.grade)AS avg
      FROM Students s1
      NATURAL JOIN EnrolledStudents e
      GROUP BY s1.sid
      ) as a
where a.avg=(select max(a.avg))

你可以看到我在SQLFIDDLE中得到的结果,你可以看到我做错了什么,我什么都得不到!这一切对我来说都是正确的......

2 个答案:

答案 0 :(得分:1)

既然是为了学习,我会先发布这个提示。想想where子句 - a是当前行。当然a.avg等于max(a.avg)

<强>更新

尝试以下方法:

SELECT s1.sname, avg(e.grade) AS avg
FROM Students s1
NATURAL JOIN EnrolledStudents e
GROUP BY s1.sid
HAVING avg = (SELECT avg(e.grade) AS avg 
  FROM EnrolledStudents e
  GROUP BY e.sid ORDER BY avg DESC LIMIT 1);

答案 1 :(得分:0)

如果没有人有更好看的答案,那么这就是最好的答案:

SELECT s.sname
FROM Students s
NATURAL JOIN EnrolledStudents e
GROUP BY s.sid
HAVING avg(e.grade) >= ALL(SELECT AVG(e.grade)
      FROM  EnrolledStudents e
      GROUP BY e.sid)