Skip to content
Advertisement

Grouping rows based on a date field in SQL Server

I have the following table exams.sql with exam scores in SQL Server. It saves the student’s ID, their score, and the test date.

The problem begins when a student takes the exam two (or more) times. I need the complete list of students with their actual qualification: in case they have been evaluated more than once, take the last date.

student_id score date
1 2 2021-01-06
1 8 2021-01-09
2 10 2021-02-14
3 9 2021-02-26
3 7 2021-03-30

The result of the query should be:

student_id score date
1 8 2021-01-09
2 10 2021-02-14
3 7 2021-03-30

This was my attempt:

And I get the following error message.

But I can’t add ‘score’ to ‘group by’ since being different scores, I would have several rows per student.

Advertisement

Answer

You can use row_number():

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement