I am trying to select top 2 records from a database table result that looks like this
SubjectId | StudentId | Levelid | total
------------------------------------------
1 | 1 | 1 | 89
1 | 2 | 1 | 77
1 | 3 | 1 | 61
2 | 4 | 1 | 60
2 | 5 | 1 | 55
2 | 6 | 1 | 45
i tried this query
SELECT rv.subjectid,
rv.total,
rv.Studentid,
rv.levelid
FROM ResultView rv
LEFT JOIN ResultView rv2
ON ( rv.subjectid = rv2.subjectid
AND
rv.total <= rv2.total )
GROUP BY rv.subjectid,
rv.total,
rv.Studentid
HAVING COUNT( * ) <= 2
order by rv.subjectid desc
but some subjects like where missing, i even tried the suggestiong frm the following link
How to select the first N rows of each group?
but i get more that two for each subjectid
what am i doing wrong?
You could use a correlated subquery:
This query constructs a single-column primary key by concatenating three columns. If you have a real primary key (like
ResultViewID
) you can substitute that forSubjectId || '-' || StudentId || '-' || LevelId
.Example at SQL Fiddle.
I hope I'm understanding your question correctly. Let me know if this is correct:
I recreated your table:
Inserted values
If you're trying to get the top group by Levelid (orderd by total field, assuming StudentID as primary key):
Yields this result:
Example of top 2 by SubjectId, ordered by total:
Result:
I hope that was the answer you were looking for.