tags:

views:

14

answers:

1

I have a simple table storing id and the score of the student. I would like to select the rank of a student id in a single sql statement. I have found several post here but they involve parameters or temp table which I don't want to mess with them as I'm using hibernate. Can someone introduce a single SQL statement which can do this job?

id    score
--------------
1      45
2      73
3      94
4      53
+2  A: 

Say your table name is student, and 3 is the student id you want to find the rank, and the rank is counted from high to low:

select count(id) + 1 as rank from student 
where score > (select score from student where id = 3)
Yau Leung
Thanks, why couldn't I have thought of this!
Kenya Kam
+1 For a single student this should work fine.
Martin Smith
+1 is not only for a single student case. If there are 2 students having the same score, it would show the co-rank. It won't work if you use "select count(id) .... where score >= ...."
Yau Leung
@Yau - What I meant was it would work fine as long as you don't want to calculate the rank in a result set returning multiple students. You would then need a triangular join and the work required grows exponentially.
Martin Smith