128k views
4 votes
List every match with the goals scored by each team as shown. This will use "CASE WHEN" which has not been explained in any previous exercises.

mdate team1 score1 team2 score2
1 July 2012 ESP 4 ITA 0
10 June 2012 ESP 1 ITA 1
10 June 2012 IRL 1 CRO 3
...
Notice in the query given every goal is listed. If it was a team1 goal then a 1 appears in score1, otherwise there is a 0. You could SUM this column to get a count of the goals scored by team1. Sort your result by mdate, matchid, team1 and team2.

User Stuckey
by
7.6k points

1 Answer

5 votes

Final answer:

The student's question is about writing a SQL query using CASE WHEN to list soccer matches and the scores for each team, then sort the results. The query includes conditional sums to calculate goals for team1 and team2, and orders the outcome by match details.

Step-by-step explanation:

The question involves listing matches with the goals scored by each team using a CASE WHEN statement in SQL. To achieve this, we would create a SQL query that selects the match date (mdate), team1, team2, and uses CASE WHEN to conditionally sum the goals for each team. We'd sum goals where a team is listed as team1, and separately sum goals where a team is listed as team2, to get their respective scores. The results are then sorted by mdate, matchid, team1, and team2.

Here is an example structure of the SQL query we might use:

SELECT mdate, team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) as score1, team2, SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) as score2
FROM matches
GROUP BY mdate, matchid, team1, team2
ORDER BY mdate, matchid, team1, team2;

Each match is listed with its date, participating teams, and the goals scored by each team, with a 1 indicating a goal by that team and a 0 otherwise. The final output would display matches and scores sorted in the specified order.

User Mawimawi
by
7.9k points