私の宿題の課題の 1 つは、各学科の平均が最も高い学生を見つけることです。
クエリ:
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
平均は正しくても、名前は正しくありません! Julia は csc で平均 100 を持っているのに、なぜ Michael が現れるのですか?
次に例を示します。
学生はコースを受講し、これらのコースの成績を取得します。例えば:
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