如何编写高效的sql查询,返回每节课中最新的学生分数(按日期)?
表格结构如下:如何编写高效的sql查询,返回每节课中最新的学生分数(按日期)?,sql,sql-server-2012,Sql,Sql Server 2012,表格结构如下: 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
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
);
您想要的索引位于(学生、课程、日期)
注意,在某些数据库中,其他方法可能会快一点。但一般来说,我发现这具有良好的性能。我认为最有效的查询通常是具有正确索引的相关子查询:
select t.*
from t
where t.date = (select max(t2.date)
from t t2
where t2.student = t.student and t2.lesson = t.lesson
);
您想要的索引位于(学生、课程、日期)
注意,在某些数据库中,其他方法可能会快一点。但是作为一般规则,我发现这有很好的性能。用你正在使用的数据库标记你的问题。用你正在使用的数据库标记你的问题。