Skip to content
Advertisement

Ranking based on two columns

Finding the Rank of the Particular User from the Database by comparing three columns.

Name | Score | Attempts | Time
test |   2   |   4      |  2019-01-29 19:50:11
tes2 |   2   |   1      |  2019-01-29 20:14:11

So the Expected Output should be

Name | Score | Attempts | Time                  | Rank
tes2 |   2   |   1      |  2019-01-29 20:14:11  |  1
test |   2   |   4      |  2019-01-29 19:50:11  |  2

If I wanted to search Rank for User ‘test’ then I should get Rank 2 as my Answer.

I have done the part from which I can get the overall Rank, but I couldn’t able to find Rank for Individual User.

This is code I have written for getting Overall Rank.

select t.*, @r := @r + 1 as `new_rank`
from  tbl t,
(select @r := 0) r
order by `Rank` asc, `Tasks` desc`

SQL Version that I’m Using is 10.1.9-MariaDB

Advertisement

Answer

Use row_number() or rank(), depending on how you want ties handled. For instance:

select t.*, row_number() over (order by rank asc, task desc) as new_rank
from t;

If you are using older versions of MySQL (as your code snippet suggests), then you can use variables, but you probably need a subquery:

select t.*, (@r := @r + 1) as new_rank
from (select t.* from tbl t order by Rank asc, Tasks desc) t cross join
     (select @r := 0) r;

One method to get a particular row:

select t.*
from (select t.*, (@r := @r + 1) as new_rank
      from (select t.* from tbl t order by Rank asc, Tasks desc) t cross join
           (select @r := 0) r
     ) t
where t.name = ?;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement