我的家庭作业的一部分是找到每个部门平均分最高的学生。
询问:
SELECT g.sid as studentID, s.sfirstname, s.dcode, AVG(grade) as average
FROM studentgrades g, student s
WHERE g.sid = s.sid
GROUP BY s.sid
结果:
1 Robert ger 80.0000
2 Julie sta 77.0000
3 Michael csc 84.0000
4 Julia csc 100.0000
5 Patric csc 86.0000
6 Jill sta 74.5000
为了回答这个问题,我运行了查询
SELECT dcode, averages.sfirstName, MAX(averages.average)
FROM (
SELECT g.sid as studentID, s.sfirstname, s.dcode, AVG(grade) as average
FROM studentgrades g, student s
WHERE g.sid = s.sid
GROUP BY s.sid) averages
GROUP BY dcode
结果:
csc Michael 100.0000
ger Robert 80.0000
sta Julie 77.0000
即使平均值是正确的,名称也不正确!朱莉娅是 csc 平均 100 分的人,那么迈克尔为什么会出现呢?
这是一个例子:
学生参加课程并获得这些课程的成绩。例如:
student1 from dept1 took course A and got grade 80
student1 from dept1 took course B and got grade 90
student2 from dept1 took course C and got grade 100
student3 from dept2 took course X and got grade 90
运行第一个查询后,我们得到每个学生的平均值
student 1 from dept1 has average 85
student 2 from dept1 has average 100
student 3 from dept2 has average 90
现在我们找到每个部门平均分最高的学生
dept1, student2, 100
dept2, student3, 90