Tags:
"leetcode",
"sql",
access_time 1-min read
Team Scores in Football Tournament
Created: March 27, 2020 by [lek-tin]
Last updated: March 27, 2020
Solution (Union)
SELECT t.team_id,
t.team_name,
IFNULL(SUM(p.points), 0) AS num_points
FROM Teams t
LEFT JOIN
(
SELECT host_team as team_id,
CASE
WHEN host_goals > guest_goals THEN 3
WHEN host_goals = guest_goals THEN 1
ELSE 0
END as points
FROM Matches
UNION ALL
SELECT guest_team as team_id,
CASE
WHEN host_goals < guest_goals THEN 3
WHEN host_goals = guest_goals THEN 1
ELSE 0
END as points
FROM Matches
) AS p
ON t.team_id = p.team_id
GROUP BY t.team_id
ORDER BY num_points DESC, team_id