w3resource

SQL Exercise: Find the referees who booked most number of players

SQL soccer Database: Joins Exercise-55 with Solution

55. From the following tables, write a SQL query to find those referees who booked the most number of players. Return referee name, number of matches.

Sample table: player_booked


Sample table: match_mast


Sample table: referee_mast


Sample Solution:

SQL Code:

SELECT c.referee_name,
       count(b.match_no)
FROM player_booked a
JOIN match_mast b ON a.match_no=b.match_no
JOIN referee_mast c ON b.referee_id=c.referee_id
GROUP BY referee_name
HAVING count(b.match_no)=
  (SELECT max(mm)
   FROM
     (SELECT count(b.match_no) mm
      FROM player_booked a
      JOIN match_mast b ON a.match_no=b.match_no
      JOIN referee_mast c ON b.referee_id=c.referee_id
      GROUP BY referee_name) hh);

Sample Output:

   referee_name   | count
------------------+-------
 Mark Clattenburg |    21
(1 row)

Code Explanation:

The provided query in SQL query that retrieves player_booked table aliased as a, match_mast table aliased as b, and referee_mast table aliased as c and returns the name of the referee(s) who received the maximum number of bookings.
The JOIN keyword joins the player_booked and match_mast tables based on the match_no column, the match_mast and the referee_mast tables based on the referee_id column.
The GROUP BY statement groups the results by referee_name.
The HAVING clause filters the results to only include referees who received the maximum number of bookings.
The subquery within the HAVING clause selects the maximum number of bookings from the group of referees.
The query returns the name(s) of the referee(s) who received the maximum number of bookings.

Practice Online


Sample Database: soccer

soccer database relationship structure

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Find the referees and number of booked he made.
Next SQL Exercise: Find the player of each team who wear jersey number 10.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

SQL: Tips of the Day

What is the best way to paginate results in SQL Server?

SELECT  *
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *
          FROM      Orders
          WHERE     OrderDate >= '1980-01-01'
        ) AS RowConstrainedResult
WHERE   RowNum >= 1
    AND RowNum < 20
ORDER BY RowNum

Database: SQL Server

Ref: https://bit.ly/3MGrNlk

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook