You have two tables: Teams and Matches. Write a SQL query to report comprehensive league statistics for each team.
Teams table:
team_id(int): Unique team identifierteam_name(varchar): Team name
Matches table:
home_team_id(int): Home team identifieraway_team_id(int): Away team identifierhome_team_goals(int): Goals scored by home teamaway_team_goals(int): Goals scored by away team
Scoring rules:
- Win: 3 points
- Draw: 1 point each
- Loss: 0 points
Return statistics including team name, matches played, points, goals for/against, and goal difference. Order by points (descending), then goal difference (descending), then team name (ascending).
Table Schema
| Column Name | Type | Description |
|---|---|---|
team_id
PK
|
int | Unique identifier for each team |
team_name
|
varchar | Name of the team |
| Column Name | Type | Description |
|---|---|---|
home_team_id
PK
|
int | ID of the home team |
away_team_id
PK
|
int | ID of the away team |
home_team_goals
|
int | Goals scored by home team |
away_team_goals
|
int | Goals scored by away team |
Input & Output
| team_id | team_name |
|---|---|
| 1 | Team A |
| 2 | Team B |
| 3 | Team C |
| home_team_id | away_team_id | home_team_goals | away_team_goals |
|---|---|---|---|
| 1 | 2 | 3 | 1 |
| 2 | 3 | 1 | 1 |
| 3 | 1 | 0 | 2 |
| team_name | matches_played | points | goal_for | goal_against | goal_diff |
|---|---|---|---|---|---|
| Team A | 2 | 6 | 5 | 1 | 4 |
| Team B | 2 | 1 | 2 | 4 | -2 |
| Team C | 2 | 1 | 1 | 3 | -2 |
Team A wins both matches (3-1 vs Team B home, 2-0 vs Team C away) for 6 points. Team B draws with Team C and loses to Team A for 1 point. Team C draws with Team B and loses to Team A for 1 point. Teams B and C tie on points and goal difference, so ordered alphabetically.
| team_id | team_name |
|---|---|
| 1 | Alpha |
| 2 | Beta |
| home_team_id | away_team_id | home_team_goals | away_team_goals |
|---|---|---|---|
| 1 | 2 | 2 | 2 |
| team_name | matches_played | points | goal_for | goal_against | goal_diff |
|---|---|---|---|---|---|
| Alpha | 1 | 1 | 2 | 2 | 0 |
| Beta | 1 | 1 | 2 | 2 | 0 |
Single match ends in 2-2 draw. Both teams get 1 point each, same goal difference (0), so ordered alphabetically by team name.
Constraints
-
1 ≤ team_id ≤ 1000 -
1 ≤ team_name.length ≤ 50 -
0 ≤ home_team_goals, away_team_goals ≤ 20 -
Each match has different
home_team_idandaway_team_id