IniziaInizia gratis

Putting the CTEs together

Now that you've created the two subqueries identifying the home and away team opponents, it's time to rearrange your query with the home and away subqueries as Common Table Expressions (CTEs). You'll notice that the main query includes the phrase, SELECT DISTINCT. Without identifying only DISTINCT matches, you might return a duplicate record for each game played.

Continue building the query to extract all matches played by Manchester United in the 2014/2015 season.

Questo esercizio fa parte del corso

Data Manipulation in SQL

Visualizza il corso

Istruzioni dell'esercizio

  • Declare the home and away CTEs before your main query.
  • Join your CTEs to the match table using a LEFT JOIN.
  • Select the relevant data from the CTEs into the main query.
  • Select the date from match, team names from the CTEs, and home/ away goals from match in the main query.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

-- Set up the home team CTE
___ ___ ___ (
  SELECT m.id, t.team_long_name,
	  CASE WHEN m.home_goal > m.away_goal THEN 'MU Win'
		   WHEN m.home_goal < m.away_goal THEN 'MU Loss' 
  		   ELSE 'Tie' END AS outcome
  FROM match AS m
  LEFT JOIN team AS t ON m.hometeam_id = t.team_api_id),
-- Set up the away team CTE
___ ___ (
  SELECT m.id, t.team_long_name,
	  CASE WHEN m.home_goal > m.away_goal THEN 'MU Loss'
		   WHEN m.home_goal < m.away_goal THEN 'MU Win' 
  		   ELSE 'Tie' END AS outcome
  FROM match AS m
  LEFT JOIN team AS t ON m.awayteam_id = t.team_api_id)
-- Select the date, team names and goals
SELECT DISTINCT
    ___.___,
    ___.___ AS home_team_name,
    ___.___ AS away_team_name,
    ___.___,
    m.away_goal
-- Join the CTEs onto the match table
FROM match AS m
___ JOIN ___ ON m.id = ___
___ JOIN ___ ON m.id = ___
WHERE m.season = '2014/2015'
      AND (home.team_long_name = 'Manchester United' 
           OR away.team_long_name = 'Manchester United');
Modifica ed esegui il codice