题目
表:Enrollments
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| student_id | int |
| course_id | int |
| grade | int |
+---------------+---------+
(student_id, course_id) 是该表的主键。
编写一个 SQL 查询,查询每位学生获得的最高成绩和它所对应的科目,若科目成绩并列,取 course_id 最小的一门。查询结果需按 student_id 增序进行排序。
查询结果格式如下所示:
Enrollments 表:
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 2 | 2 | 95 |
| 2 | 3 | 95 |
| 1 | 1 | 90 |
| 1 | 2 | 99 |
| 3 | 1 | 80 |
| 3 | 2 | 75 |
| 3 | 3 | 82 |
+------------+-----------+-------+
Result 表:
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 1 | 2 | 99 |
| 2 | 2 | 95 |
| 3 | 3 | 82 |
+------------+-----------+-------+
解答
先选出每个学生的最高成绩
select E.student_id, max(E.grade) as max_grade
from Enrollments as E
group by E.student_id;
用二元in选择出最高成绩对应的情况
select E1.student_id, E1.course_id, E1.grade
from Enrollments as E1
where (E1.student_id, E1.grade) in (select E.student_id, max(E.grade) as max_grade
from Enrollments as E
group by E.student_id);
同分时 对id grade 分组 取最小的课程id即可
select E1.student_id, min(E1.course_id) as course_id, E1.grade
from Enrollments as E1
where (E1.student_id, E1.grade) in (select E.student_id, max(E.grade) as max_grade
from Enrollments as E
group by E.student_id)
group by E1.student_id, E1.grade;
其实对id分组即可
select E1.student_id, min(E1.course_id) as course_id, E1.grade
from Enrollments as E1
where (E1.student_id, E1.grade) in (select E.student_id, max(E.grade) as max_grade
from Enrollments as E
group by E.student_id)
group by E1.student_id
order by E1.student_id;