﻿ SQL: Identify countries where referees managed most matches

SQL Exercise: Identify countries where referees managed most matches

SQL soccer Database: Joins Exercise-50 with Solution

50. From the following tables, write a SQL query to find the countries from where the referees managed most of the matches. Return country name, number of matches.

Sample table: match_mast

Sample table: referee_mast

Sample table: soccer_country

Sample Solution:

SQL Code:

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

Sample Output:

``` country_name | count
--------------+-------
England      |     7
(1 row)
```

Code Explanation:

The said query in SQL that selects the name of countries and the count of match numbers in the match_mast table for each country.
The JOIN clause in this query then joins the match_mast and referee_mast tables based on the referee_id column and joins the results with soccer_country tables based on the country_id column.
The query groups the results by country name using the GROUP BY clause and applies an aggregate function, count(), to count the number of match numbers for each country. The HAVING clause filters the results to only show the countries whose count of match numbers is equal to the maximum count of match numbers among all countries. The maximum count of match numbers is obtained by a subquery that selects the count of match numbers for each country and then selects the maximum count from those results.

Practice Online

Sample Database: soccer

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

Previous SQL Exercise: The number of matches each referee has managed.
Next SQL Exercise: Find the referees managed the number of matches.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

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