-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1841.sql
31 lines (30 loc) · 1.01 KB
/
1841.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- [ LeetCode ] 1841. League Statistics
SELECT
team_name,
COUNT(team_id) AS matches_played,
SUM(CASE team_id
WHEN home_team_id THEN
CASE
WHEN home_team_goals > away_team_goals THEN 3
WHEN home_team_goals = away_team_goals THEN 1
ELSE 0
END
WHEN away_team_id THEN
CASE
WHEN away_team_goals > home_team_goals THEN 3
WHEN away_team_goals = home_team_goals THEN 1
ELSE 0
END
END) AS points,
SUM(IF(team_id = home_team_id, home_team_goals, away_team_goals)) AS goal_for,
SUM(IF(team_id = home_team_id, away_team_goals, home_team_goals)) AS goal_against,
SUM(IF(team_id = home_team_id, (home_team_goals - away_team_goals), (away_team_goals - home_team_goals))) AS goal_diff
FROM Teams
JOIN Matches
ON (
team_id = home_team_id
OR
team_id = away_team_id
)
GROUP BY team_id, team_name
ORDER BY points DESC, goal_diff DESC, team_name ASC;