如何编写高效的 sql 查询 return 每节课的最新学生分数(按日期)?

How to write efficient sql query that return latest student score(by date) in each lesson?

table结构如下:

student lesson  score   Date
Allen   Math    12      9/11/12
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 15      9/11/12
Joe     Physics 13      9/11/15

结果应该是:

student lesson  score   Date
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 13      9/11/15

我认为最普遍有效的查询是具有正确索引的相关子查询:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.student = t.student and t2.lesson = t.lesson
               );

您想要的索引在(student, lesson, date)

请注意,在某些数据库中,其他方法可能会更快一些。但作为一般规则,我发现这具有良好的性能。