我正在尝试对学生所参加的每个学科的TestScores表中的所有最新考试成绩进行汇总。
STUDENT_ID SUBJECT SCORE TEST_DATE
1 math 90% 11/5/2018
1 math 88% 1/12/2019
1 science 74% 12/9/2018
2 math 79% 10/10/2018
2 science 68% 2/25/2019
1 science 72% 6/14/2018
2 art 93% 9/22/2018
3 art 73% 10/20/2018
Desired output:
STUDENT_ID SUBJECT SCORE TEST_DATE
1 math 88% 1/12/2019
1 science 74% 12/9/2018
2 math 79% 10/10/2018
2 science 68% 2/25/2019
2 art 93% 9/22/2018
3 art 73% 10/20/2018
答案 0 :(得分:0)
您可以利用ROW_NUMBER来做到这一点。
select STUDENT_ID
, SUBJECT
, SCORE
, TEST_DATE
from
(
select STUDENT_ID
, SUBJECT
, SCORE
, TEST_DATE
, RowNum = ROW_NUMBER()over(partition by STUDENT_ID, SUBJECT order by TEST_DATE DESC)
from TestScores
) x
where x.RowNum = 1
答案 1 :(得分:0)
与此:
select student_id, subject, max(test_date) maxdate
from tablename
group by student_id, subject
您会获得每个学生和学科的所有最新日期,
因此您将其加入表格并获得所需的结果:
select t.*
from tablename t inner join (
select student_id, subject, max(test_date) maxdate
from tablename
group by student_id, subject
) g
on g.student_id = t.student_id and g.subject = t.subject and g.maxdate = t.test_date