2

I have a table GAMES with this information:

- Id_Game (int)
- Id_Referee1 (int)
- Id_Referee2 (int)

These are some rows:

ID_GAME    ID_REFEREE1    ID_REFEREE2
1          1000           728
2          1004           813
3          728            1004
4          1004           1000

I want to have a list with the number of games that a referee has officiated, doesn't matter if as a Referee1 or Referee2. In this case, I would like to receive this list order by number of games DESC.

REFEREE    NUMBER OF GAMES
1004       3
728        2
1000       2
813        1

Which would be the SQL query? I have no idea of how to join fields Id_Referee1 and Id_Referee2...

THANKS

4 Answers 4

3

I think:

select referee, count(*) from (
    select id_game, id_referee1 as referee
    from games
    union
    select id_game, id_referee2 as referee
    from games
)
group by referee
Sign up to request clarification or add additional context in comments.

3 Comments

you are assuming id_game is unique - which of course it probably is but @Arturo doesn't specify
@JackPDouglas You're right, but you are assuming that referee1 != referee2 - which he also didn't specify ;)
Thank you both, I am testing but it seems OK. Of course Id_game is unique and referee1 != referee2 in the same row. THANKS. I will tell you in a minute.
0

assuming id_referee1!=id_referee2 for all possible rows (probably using a check constraint):

select referee, count(*) as number_of_games 
from( select id_referee1 as referee from games 
      union all 
      select id_referee2 from games )
group by referee
order by count(*) desc;

if you don't want to make that assumption:

select referee, count(*) as number_of_games 
from( select id_referee1 as referee from games 
      union all 
      select id_referee2 
      from games 
      where id_referee1 is null or id_referee1!=id_referee2 )
group by referee
order by count(*) desc;

Comments

0
SELECT ID_REFEREE1, count( * ) as no_of_games
FROM games
GROUP BY ID_REFEREE1
ORDER BY 2

1 Comment

If you post code or XML, please highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
0

I think something is wrong because I get an error with this query:

SELECT Referee, count(*) FROM 
(
  (SELECT Id_Game, Id_Referee1 as Referee FROM Games) 
  UNION ALL 
  (SELECT Id_Game, Id_Referee2 as Referee FROM Games)
) GROUP BY Referee

Can you see what is wrong? THANKS

2 Comments

In fact, the error I get is "#1248 - Every derived table must have its own alias". Any help?
Some RDBMSs (eg MySQL, postgres) insist on an alias for each subquery, so select * from (select * from games) throw an error but select * from (select * from games) as g is fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.