我有三个表,Student,Grd,Course,我想选择每门课程的最佳成绩和学生姓名。
这是我的查询,返回所有学生-名称和年级-但我只想为每门课程取得最佳成绩。
select
student.[name], Course.[Name] as course, max((GRD.Number)) as Grade
from
GRD
join
Course on Course.CO_ID = GRD.CO_ID
join
Student on Student.ST_ID = GRD.ST_ID
group by
course.[Name], Student.[Name]
我正在使用Sql服务器
如果您使用的是MySQL 8.0,PostgreSQL,SQL Server或Oracle,则可以使用以下方法解决您的问题。
select
student_name,
course,
Grade
from
(
select
s.[name] as student_name,
c.[Name] as course,
max(g.Number) as Grade,
row_number() over (partition by c.[Name] order by max(g.Number) desc) as rnk
from GRD g
join Course c
on c.CO_ID = g.CO_ID
join Student s
on s.ST_ID = g.ST_ID
group by
c.[Name],
s.[Name]
) val
where rnk = 1