Reputation: 63
I have problem getting row from a max column, here the illustration : http://sqlfiddle.com/#!3/15207/9
basically I want to get the student's highest grade along with the grade-id (gid). but the query is not right because of using max grade id which will return 2.
First course taken, the student got D (1 point). Second time course taken, the student got E (0 point).
The gradeid for that 1 point is 1.
I expect the query result is: 1 (userid), 1 (subjectid), 1 (gradeid), 1 (score)
Thanks
UPDATE 01:
The more improved example: http://sqlfiddle.com/#!3/97997/2
Upvotes: 1
Views: 227
Reputation: 263893
UPDATE 1
WITH highestScore
AS
(
SELECT a.uid StudentID,
a.uname StudentName,
b.Score,
c.cname CourseName,
c.semester,
d.sname SubjectName, d.sid,
DENSE_RANK() OVER (PARTITION BY a.uid, d.sid
ORDER BY b.Score DESC) rn
FROM Users a
INNER JOIN Grades b
ON a.uid = b.uid
INNER JOIN Courses c
ON b.cid = c.cid
INNER JOIN Subjects d
ON c.sid = d.sid
)
SELECT StudentID, StudentName, CourseName, semester,
SubjectName, Score
FROM highestScore
WHERE StudentID = 1 AND -- StudentID
sid = 1 AND -- SubjectID
RN = 1 -- leave this as is (rank of the highest score)
Upvotes: 3