Search code examples
mysqlgreatest-n-per-group

Finding winners of races in SQL


I have a table with results for users, participating in different races. The one with the highest performance score in each race is the winner of each race. So in the example below Alice has 0 wins, Bob has 1 and Chris has 2 wins.

What I need, is to be able to calculate for a given user how many wins he/she has across all races he/she participated in, and also another number of how many podium results (1st second or 3rd place).

Is this even possible with SQL alone? I'm using MySQL

P.S. I have no idea why the table isn't rendered correctly, it looks perfect in the preview, so if anyone can fix it, it's much appreciated.

RaceID UserID Performance
1 Alice 90
1 Bob 100
2 Alice 100
2 Bob 90
2 Chris 110
3 Alice 90
3 Bob 80
3 Chris 150

Solution

  • You can use NOT EXISTS to get the rows of wins for each user and sum them:

    SELECT t1.UserID,
           SUM(NOT EXISTS(SELECT 1 FROM tablename t2 WHERE t2.RaceID = t1.RaceID AND t2.Performance > t1.Performance)) wins
    FROM tablename t1
    GROUP BY t1.UserID
    

    If your version of MySql is 8.0+ you can do it with MAX() window function and aggregation:

    SELECT UserID, 
           SUM(Performance = max_performance) wins
    FROM (
      SELECT *, MAX(Performance) OVER (PARTITION BY RaceID) max_performance
      FROM tablename
    ) t
    GROUP BY UserID
    

    See the demo.