Search code examples
sqlaggregate-functionsgreatest-n-per-groupgroupwise-maximum

SQL selecting the rows with the maximum value in a table ordered by a column from another


I have 2 tables which, simplified, look like this:

Name     Server_id     score
-----------------------------
John         1           300
John         2           400
Mary         2           321
John         1           100
Mary         1            50 
Mary         2            10


Server_id     game
-------------------
   1           pong
   2           Mario

Each player can have multiple scores associated with any Server. And to a Server, corresponds a game.

Now I want to execute a select statement which returns the maximum score for player, in each game. Something like this:

Name     game     score
-----------------------
John     pong     300
John     Mario    400
Mary     pong     50
Mary     Mario    321

Solution

  • Unless I am missing something, this is simply a JOIN and GROUP BY:

    select t1.name, t2.game, max(t1.score)
    from table1 t1 join
         table2 t2
         on t1.server_id = t2.server_id
     group by t1.name, t2.game;