A football tournament records its teams and every match played. Write a SQL query returning team_id, team_name and num_points for every team after all matches.
Points are awarded per match:
-
Win (more goals than the opponent): 3 points.
-
Draw (same number of goals): 1 point.
-
Loss: 0 points.
Teams with no matches appear with 0 points. Order by num_points descending, ties by team_id ascending.
Input Table(s)
Teams
| Column | Type | Meaning |
|---|
| team_id | INT | Team id |
| team_name | VARCHAR(50) | Team name |
Primary key: team_id.
Matches
| Column | Type | Meaning |
|---|
| match_id | INT | Match id |
| host_team | INT | team_id of the host team |
| guest_team | INT | team_id of the guest team |
| host_goals | INT | Goals scored by the host team |
| guest_goals | INT | Goals scored by the guest team |
Primary key: match_id. host_team and guest_team both reference Teams.team_id.
Output Contract
-
Columns, in this order:
team_id
,
team_name
,
num_points
.
-
Exactly one row per team in
Teams
, including teams that played no match (
num_points
= 0).
-
num_points
is an integer, the sum of the points the team earned across all its matches.
-
Order by
num_points
descending, then
team_id
ascending.
team_id
is the primary key, so the order is unique.
Example
Teams
| team_id | team_name |
|---|
| 10 | Lions |
| 20 | Tigers |
| 30 | Bears |
| 40 | Wolves |
| 50 | Eagles |
Matches
| match_id | host_team | guest_team | host_goals | guest_goals |
|---|
| 1 | 10 | 20 | 3 | 0 |
| 2 | 30 | 10 | 2 | 2 |
| 3 | 10 | 50 | 5 | 1 |
| 4 | 20 | 30 | 1 | 0 |
| 5 | 50 | 30 | 1 | 0 |
Expected result:
| team_id | team_name | num_points |
|---|
| 10 | Lions | 7 |
| 20 | Tigers | 3 |
| 50 | Eagles | 3 |
| 30 | Bears | 1 |
| 40 | Wolves | 0 |
Lions win matches 1 and 3 and draw match 2 as the guest, for 7 points. Tigers and Eagles each have one win and one loss, so they tie on 3 and the lower team_id comes first. Bears have one draw and two losses, and Wolves played no match.
Constraints and Clarifications
-
Teams
has 1 to 100 rows and
Matches
has 0 to 100 rows.
-
host_team
and
guest_team
always reference existing teams, and
host_team != guest_team
.
-
host_goals
and
guest_goals
are non-NULL for every match.
-
The same two teams can meet more than once. Every match counts.
-
Team names are not guaranteed to be unique, so results are per
team_id
.