3

课程(cid、cname、描述)

教授(pid,pname)

教学(tid、cid、pid、年、学期、系)

学生(sid、lname、fname、b_date、部门)

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中得到的结果,你可以看到我做错了什么,我不明白!这一切对我来说似乎都是正确的......

4

2 回答 2

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);
于 2012-07-03T14:46:32.910 回答
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)
于 2012-07-03T15:14:44.063 回答