LeetCode(数据库)- 联赛信息统计
Posted 程序员牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(数据库)- 联赛信息统计相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略。
解题思路:略。
AC 代码
-- 解决方案(1)
SELECT distinct team_name,
COUNT(*) AS matches_played,
SUM(
CASE
WHEN (team_id=home_team_id AND home_team_goals>away_team_goals) OR
(team_id=away_team_id AND home_team_goals<away_team_goals) THEN 3
WHEN (team_id=home_team_id AND home_team_goals<away_team_goals) OR
(team_id=away_team_id AND home_team_goals>away_team_goals) THEN 0
ELSE 1 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)) - SUM(IF(team_id=home_team_id,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
ORDER BY points DESC, goal_diff DESC, team_name ASC
-- 解决方案(2)
WITH t1 AS(SELECT team_id, COUNT(*) matches_played
FROM (SELECT home_team_id team_id FROM Matches
UNION ALL
SELECT away_team_id FROM Matches) t
GROUP BY team_id),
t_point AS(SELECT home_team_id, away_team_id,
SUM(IF(home_team_goals > away_team_goals, 3, IF(home_team_goals = away_team_goals, 1, 0))) home_points,
SUM(IF(home_team_goals > away_team_goals, 0, IF(home_team_goals = away_team_goals, 1, 3))) away_points
FROM Matches
GROUP BY home_team_id, away_team_id),
t2 AS(SELECT team_id, SUM(points) points
FROM (SELECT home_team_id team_id, home_points points FROM t_point
UNION ALL
SELECT away_team_id, away_points FROM t_point) t
GROUP BY team_id),
t3 AS(SELECT team_id, SUM(goal_for) goal_for, SUM(goal_against) goal_against, SUM(goal_for) - SUM(goal_against) goal_diff
FROM (SELECT home_team_id team_id, SUM(home_team_goals) goal_for, SUM(away_team_goals) goal_against
FROM Matches
GROUP BY home_team_id
UNION ALL
SELECT away_team_id team_id, SUM(away_team_goals) goal_for, SUM(home_team_goals) goal_against
FROM Matches
GROUP BY away_team_id) t
GROUP BY team_id)
SELECT team_name, matches_played, points, goal_for, goal_against, goal_diff
FROM Teams JOIN t1 USING(team_id) JOIN t2 USING(team_id) JOIN t3 USING(team_id)
ORDER BY points DESC, goal_diff DESC, team_name
以上是关于LeetCode(数据库)- 联赛信息统计的主要内容,如果未能解决你的问题,请参考以下文章
蓝桥杯·寒假百校真题大联赛(大学B组)(第5期)题目讲解:日志统计
蓝桥杯·寒假百校真题大联赛(大学B组)(第5期)题目讲解:日志统计
蓝桥杯·寒假百校真题大联赛(大学B组)(第5期)题目讲解:日志统计