Hi, I can't figure out how to write this query, I'm sure it's something silly, but I just can't figure it out!!
I have a table with student's grades in different classes they took,
example-

studId, classId, yearClassTaken, grade
1, 11, 2008, 90
1, 12, 2008, 78
1, 13, 2007, 30
1, 13, 2008, 70
1, 13, 2009, 80

2, 11, 2009, 65
......
....
...

I want to get every class only ONCE, and I want to get the LAST time the class was taken, so that later I can calculate the avg of each student. so in my example above, student 1 took the class 13 three times, so I want to get this row:
1, 11, 2008, 90
1, 12, 2008, 78
1, 13, 2009, 80
2, 11, 2009, 65

I put a max(yearClassTaken) to get the latest year but it gives me the grade of another year!
1, 13, 2011, 70

what am I doing wrong?

SELECT studId,
classId,
max(yearClassTaken) as year,
grade,
FROM `tblstudent_grades`

p.s I don't want to put max() on grade, because the point is not to get the highest grade, but rather the last grade.

SELECT a.studId,
a.classId,
a.yearClassTaken as year,
a.grade,
FROM `tblstudent_grades` a inner join 
(SELECT studId,
classId,
max(yearClassTaken) as year,
FROM `tblstudent_grades` group by studId,classId) b on a.studid=b.studid and a.classid=b.classid and a.yearClassTaken =b.year
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.