假设我有一个 MySQL 表 signed_up
,其中包含 student_id、course_id 和marks
列。我想取回每个学生的 student_id、course_id
和最大 mark
。如果学生在多门类(class)中获得相同的mark
,我想选择course_id
最小的行。最后,我想显示按 student_id
递增排序的这些结果。
这是我的尝试,但输出不正确:
select student_id, course_id, max(grade) from signed_up
where course_id =
(select min(course_id) from signed_up s where s.student_id = student_id)
group by student_id, course_id
order by student_id asc;
我返回一个结果集,其中 course_id
全部为 1。这让我觉得我搞乱了 where
子句中的子查询。
有什么建议吗?
最佳答案
希望以下查询对您有所帮助:
select su.student_id, min(su.course_id), su.grade from signed_up su where
su.grade = (select max(grade) from signed_up s where s.student_id = su.student_id)
group by su.student_id order by su.student_id asc;
关于mysql - SQL:用子查询打破平局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192025/