LeetCode:Database 70.查询球队积分
Posted Xiao Miao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 70.查询球队积分相关的知识,希望对你有一定的参考价值。
要求:写出一条SQL语句以查询每个队的 team_id,team_name 和 num_points。结果根据 num_points 降序排序,如果有两队积分相同,那么这两队按 team_id 升序排序。
积分规则如下:
赢一场得三分;
平一场得一分;
输一场不得分。
Table: Teams的结构
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| team_id | int |
| team_name | varchar |
+---------------+----------+
此表的主键是 team_id,表中的每一行都代表一支独立足球队。
Table: Matches的结构
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| match_id | int |
| host_team | int |
| guest_team | int |
| host_goals | int |
| guest_goals | int |
+---------------+---------+
此表的主键是 match_id,表中的每一行都代表一场已结束的比赛,比赛的主客队分别由它们自己的 id 表示,他们的进球由 host_goals 和 guest_goals 分别表示。
Teams 表:
+-----------+--------------+
| team_id | team_name |
+-----------+--------------+
| 10 | Leetcode FC |
| 20 | NewYork FC |
| 30 | Atlanta FC |
| 40 | Chicago FC |
| 50 | Toronto FC |
+-----------+--------------+
Matches 表:
+------------+--------------+---------------+-------------+--------------+
| match_id | host_team | guest_team | host_goals | guest_goals |
+------------+--------------+---------------+-------------+--------------+
| 1 | 10 | 20 | 3 | 0 |
| 2 | 30 | 10 | 2 | 2 |
| 3 | 10 | 50 | 5 | 1 |
| 4 | 20 | 30 | 1 | 0 |
| 5 | 50 | 30 | 1 | 0 |
+------------+--------------+---------------+-------------+--------------+
Result Table:
+------------+--------------+---------------+
| team_id | team_name | num_points |
+------------+--------------+---------------+
| 10 | Leetcode FC | 7 |
| 20 | NewYork FC | 3 |
| 50 | Toronto FC | 3 |
| 30 | Atlanta FC | 1 |
| 40 | Chicago FC | 0 |
+------------+--------------+---------------+
SQL语句:
注:也可使用union all 将主客队team_id当做一列,成绩当做一列,通过Group by分组求和,下面是同一个team_id的在主队成绩与在客队的成绩求和(将成绩分成两列)
with a as(
select host_team,guest_team,
case when host_goals>guest_goals then 3 when host_goals=guest_goals then 1 else 0 end as p1,
case when host_goals<guest_goals then 3 when host_goals=guest_goals then 1 else 0 end as p2
from matches)
select b.team_id,b.team_name,ifnull(c.p3,0)+ifnull(d.p4,0) as num_points
from teams b
left join
(select host_team,sum(p1) as p3
from a
group by host_team
)c
on b.team_id=c.host_team
left join
(select guest_team,sum(p2) as p4
from a
group by guest_team)d
on b.team_id=d.guest_team
order by num_points desc,b.team_id asc;
以上是关于LeetCode:Database 70.查询球队积分的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode:Database 69.查询结果的质量和占比