w3resource
Soccer Database Exercises

SQL exercises on soccer Database: Find the player who scored the last goal for Portugal against Hungary

SQL soccer Database: Subqueries Exercise-8 with Solution

8. Write a query in SQL to find the player who scored the last goal for Portugal against Hungary.

Sample table: soccer_country


Sample table: goal_details


Sample table: match_details


Sample table: player_mast


Sample Solution:

SQL Code:

SELECT player_name 
FROM player_mast 
WHERE player_id=(
  SELECT player_id 
  FROM goal_details 
    where match_no=(SELECT match_no FROM match_details 
WHERE team_id=(
SELECT country_id FROM soccer_country 
WHERE country_name='Hungary') 
or team_id=(SELECT country_id FROM soccer_country 
WHERE country_name='Portugal') 
GROUP BY match_no HAVING COUNT(DISTINCT team_id)=2) 
    AND team_id=(SELECT team_id
FROM soccer_country a, soccer_team b
WHERE a.country_id=b.team_id AND country_name='Portugal') 
    AND goal_time=(
      SELECT max(goal_time) 
      FROM goal_details 
        WHERE match_no=(SELECT match_no FROM match_details 
WHERE team_id=(
SELECT country_id FROM soccer_country 
WHERE country_name='Hungary') 
or team_id=(SELECT country_id FROM soccer_country 
WHERE country_name='Portugal') 
GROUP BY match_no HAVING COUNT(DISTINCT team_id)=2) AND team_id=(
SELECT team_id
FROM soccer_country a, soccer_team b
WHERE a.country_id=b.team_id AND country_name='Portugal'))
                );

Sample Output:

    player_name
--------------------
 Cristiano Ronaldo
(1 row)

Query Visualization:

Duration:

Query visualization of Find the player who scored the last goal for Portugal against Hungary - Duration

Rows:

Query visualization of Find the player who scored the last goal for Portugal against Hungary - Rows

Cost:

Query visualization of Find the player who scored the last goal for Portugal against Hungary - Cost

Practice Online


Sample Database: soccer

soccer database relationship structure

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

Previous: Write a query in SQL to find the teams who played the heighest audence match.
Next: Write a query in SQL to find the 2nd highest stoppage time which had been added in 2nd half of play.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming