there is a table
student|Year|Marks
ABC|2023|98
XYZ|2021|100
MNO|2019|81
XYZ|2020|98
MNO|2018|98
ABC|2022|100
the result should just show
XYZ|2021|100
i am trying to create the query as
with cte as
(select *, row_number() over (partition by name, year order by marks) as rn
from table1)
select name, year, marks
from CTE
where rn = 1
the condition which i am unable to include is the comparison of the marks in between the 2 years data.
2
Answers
One option could be using LAG() Over() analytic function to get last year’s marks in the same row allowing you to filter the data for any condition you need (marks better, worse, equal …)
… so, if you add Where clause to the outer query you could get the expected result …
You can use
NOT EXISTS
to return each student’s last year result as long as it has the student’s highest marks.MySQL users might want to do a self
LEFT JOIN
instead:MySQL version 8 users can use
row_number()
window function, partition by student, to make sure the latest year also has the highest marks:Demo: https://dbfiddle.uk/vyNa1iq7 (based on @nbk’s fiddle, thanks!)