Question

I have two tables. It's about chess game and it's players.

In the first table I have the details about the player. In the second table I have the details about the game (player 1, player 2) , (game type).

The two tables are linked together.(Two refferences, player 1 linked with id from first table, player 2 again linked with id from first table)

My task is to do this interrogation.

I have to display, the player with most games played.

The problem is that i have this player in two tables. So far I managed to display the maximum of games played by a player from a single column:

select Player1,count(Player1) as number_ofgames
group by Player1 
having count(Player 1) in 
(select max(count(Player 1)) from games group by Player1);
Was it helpful?

Solution

I'm not sure about your table structures therefore assuming your player table has column player_id as well as game table player1_id and player2_id this query may met your requirements on Oracle 12c.

select
    p.player_id,
    count(*) as games_played

from
    player p join game g on p.player_id = g.player1_id or p.player_id = g.player2_id

group by
    p.player_id

order by
    2 desc

fetch first 1 rows with ties;

Using the WITH TIES clause may result in more rows being returned if multiple rows match the value of the Nth row.

For more details read http://www.oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1.php#top-n.

In MySQL use LIMIT instead:

select
    p.player_id,
    count(*) as games_played

from
    player p join game g on p.player_id = g.player1_id or p.player_id = g.player2_id

group by
    p.player_id

order by
    2 desc

limit 1;

Read more here: http://dev.mysql.com/doc/refman/5.0/en/select.html.

OTHER TIPS

If you are using a 11G R2, you could use listagg function. If not, it will be easy to find a different way

   With distrib as
                (select O as dabegin, 17 as daend, 'under 18' as category from dual
                union all 
                select 18 as dabegin ,25 as daend, 'between 18-25' as category from dual
                union all 
                select 26 as dabegin ,30 as daend,  'between 26-30' as category from dual
                 )
                , games as
                (select
                    p.player_id,
                    count(*) as games_played

    from
        player p join game g on p.player_id = g.player1_id or p.player_id = g.player2_id

group by
    p.player_id)
select max(games_played), listagg(player_id,',') WITHIN GROUP (ORDER BY player_id) as 'winner(s)', category
from distrib d, games g, players p
where p.player_id=g.player_id
and g. age between d.dabegin and daend
group by g.category
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top