我有以下四个表格,其中包含学生信息,讲座信息,参加讲座的信息和考试。
使用 从考试GROUP BY Student_id中平均选择Student_id,AVG(分数); 我得到了每个学生获得的平均成绩列表。
我如何将其与MAX函数结合使用以获取列表中平均值最高的学生的ID,姓名和平均值?
student_id
student_name
lecture_id
Lesson_name
ECTS
id
student_id
tutorial_id
id
Student_id
Lecture_id
标记
答案 0 :(得分:0)
您可以将这样的SQL与ORDER BY ... DESC
子句一起使用来获取MAX
对于MySQL:
SELECT e.Student_id, s.student_name, AVG(marks) as "average"
FROM exams e
LEFT JOIN students s ON e.Student_id = s.Student_id
GROUP BY e.Student_id, s.student_name
ORDER BY "average" DESC
LIMIT 1;
对于Oracle:
SELECT * FROM
(
SELECT q.*, row_number() over (order by "average" desc) as rn
FROM
(
SELECT e.Student_id, s.student_name, AVG(marks) as "average"
FROM exams e
LEFT JOIN students s ON e.Student_id = s.Student_id
GROUP BY e.Student_id, s.student_name
) q
)
WHERE rn = 1;