I have students exam scores for a specific subject in database. Students are given a test and they may get a score of 0 - more than 100.
I would would like to rank
students based on their score. Here is the simple score.
MariaDB [phpa]> select id, name, score FROM users WHERE id < 10;
+----+---------------+-------+---------+-
| id | name | score | rank |
+----+---------------+-------+---------+-
| 1 | yngiid | 97 | |
| 2 | viyrp | 217 | |
| 3 | pae | 599 | |
| 4 | spohl | 284 | |
| 5 | shl | 295 | |
| 6 | okeer | 73 | |
| 7 | jmaany | 657 | |
| 8 | hxt | 80 | |
| 9 | yanier | 599 | |
+----+---------------+-------+---------+-
My expected output is for the rank to be
+----+---------------+-------+---------+-
| id | name | score | rank |
+----+---------------+-------+---------+-
| 7 | jmaany | 657 | 1 |
| 3 | pae | 599 | 2 |
| 9 | yanier | 599 | 2 |
| 5 | shl | 295 | 3 |
| 4 | spohl | 284 | 4 |
| 2 | viyrp | 217 | 5 |
| 1 | yngiid | 97 | 6 |
| 8 | hxt | 80 | 7 |
| 6 | okeer | 73 | 8 |
+----+---------------+-------+---------+-
Now, all I need is for the rank to from 1 - 9 but based on the score. The greater the score the lower the rank. as in jmaay
would get 1 and okeer
would be 9.
To achive this, I tried to do something like this
get = conn.query("SELECT name, score FROM users GROUP BY score ORDER BY score DESC")
users = get.fetchall()
rank = 0
for user in users:
rank += 1
conn.prepare("UPDATE users SET rank = %s WHERE name = %s", rank, user[0])
The above will iterate the users based on the score and rank them from 1. But, the problem is that since the i
increments on every loop, users who have the same score will get different ranking as in the example of pae
and yanier
both bound to get the score of 2
and 3
instead of just 2
for both.
So, to sum it up, how do I give every user a fair number of rank