我有一张桌子和足球比赛。
桌上游戏:
id
team_home (varchar)
team_away (varchar)
team_home_goals INT
team_away_goals INT
Run Code Online (Sandbox Code Playgroud)
要插入,我这样做:
insert into games values(null, 'Liverpool', 'Chelsea', 0, 0);
insert into games values(null, 'Arsenal', 'City', 1, 2);
insert into games values(null, 'ManUTD', 'Tottenham', 2, 1);
insert into games values(null, 'Chelsea', 'Arsenal', 0, 0);
insert into games values(null, 'Tottenham', 'Liverpool', 1, 0);
insert into games values(null, 'City', 'ManUTD', 2, 1);
Run Code Online (Sandbox Code Playgroud)
我需要创建一个查询以获取具有位置的表。根据上面的插入,表格将是:
1 - City 6 points
2 - ManUTD 3 points
3 - Tottenham 3 points
4 - Chelsea 2 points
5 - Liverpool 1 point
6 - Arsenal 1 point
Run Code Online (Sandbox Code Playgroud)
我为此创建的查询是针对“主队”还是“客队”。我可以运行两次此查询,然后在其他地方求和。但是我想知道是否有一种聪明的方法可以只在一个查询中完成所有操作。这就是我现在所拥有的(我两次主队,然后是客队):
select
team_home,
sum
(
case
when team_home_goals > team_away_goals then 3
when team_home_goals = team_away_goals then 1
when team_home_goals < team_away_goals then 0
end
)
as points
from
games
group by team_home;
Run Code Online (Sandbox Code Playgroud)
您可以使用UNION:
SELECT team, SUM(points) AS total_points
FROM (
SELECT team_home AS team,
CASE
WHEN team_home_goals > team_away_goals THEN 3
WHEN team_home_goals = team_away_goals THEN 1
ELSE 0
END AS points
FROM games
UNION ALL
SELECT team_away AS team,
CASE
WHEN team_away_goals > team_home_goals THEN 3
WHEN team_away_goals = team_home_goals THEN 1
ELSE 0
END AS points
FROM games ) AS t
GROUP BY team
ORDER BY total_points DESC
Run Code Online (Sandbox Code Playgroud)