Search code examples
mysqlsqlsubquerysql-order-bywindow-functions

Ranking position without duplicates


I have an issue with a query, this is my old question that was previously solved mysql get ranking position grouped with joined table

The problem is that when two players have the same score, the query returns the same ranking position, like 1-1-2-3 ecc. How can I fix this? In the player's table there are also player_tickets (that is the number of game played) and player_date that is a timestamp.

I thought to get my ranking on base of player_score first, player_tickets then, and finally player_date

This is my older query

SELECT *, 
       (SELECT 1 + Count(*) 
        FROM   players p2 
        WHERE  p2.`player_game` = p.`player_game` 
               AND p2.player_score > p.player_score  
               AND p2.player_status = 0) AS ranking 
FROM   players p 
ORDER  BY `player_game`, 
          player_score DESC

Solution

  • Just add the ranking criteria to your WHERE clause:

    SELECT *, 
      (
        SELECT 1 + COUNT(*)
        FROM   players p2 
        WHERE  p2.player_game = p.player_game 
        AND
        (
          (p2.player_score > p.player_score) OR
          (p2.player_score = p.player_score AND p2.player_tickets > p.player_tickets) OR
          (p2.player_score = p.player_score AND p2.player_tickets = p.player_tickets AND p2.player_date > p.player_date) OR
          (p2.player_score = p.player_score AND p2.player_tickets = p.player_tickets AND p2.player_date = p.player_date AND p2.player_id > p.player_id)
        )
      ) AS ranking 
    FROM players p 
    ORDER BY player_game, player_score DESC;