LeetCode 1212 查询球队积分(PostgreSQL)

数据准备

sql 复制代码
Create table If Not Exists Teams (team_id int, team_name varchar(30))
Create table If Not Exists Matches (match_id int, host_team int, guest_team int, host_goals int, guest_goals int)
Truncate table Teams
insert into Teams (team_id, team_name) values ('10', 'Leetcode FC')
insert into Teams (team_id, team_name) values ('20', 'NewYork FC')
insert into Teams (team_id, team_name) values ('30', 'Atlanta FC')
insert into Teams (team_id, team_name) values ('40', 'Chicago FC')
insert into Teams (team_id, team_name) values ('50', 'Toronto FC')
Truncate table Matches
insert into Matches (match_id, host_team, guest_team, host_goals, guest_goals) values ('1', '10', '20', '3', '0')
insert into Matches (match_id, host_team, guest_team, host_goals, guest_goals) values ('2', '30', '10', '2', '2')
insert into Matches (match_id, host_team, guest_team, host_goals, guest_goals) values ('3', '10', '50', '5', '1')
insert into Matches (match_id, host_team, guest_team, host_goals, guest_goals) values ('4', '20', '30', '1', '0')
insert into Matches (match_id, host_team, guest_team, host_goals, guest_goals) values ('5', '50', '30', '1', '0')

需求

如果球队赢了比赛(即比对手进更多的球),就得 3 分。

如果双方打成平手(即,与对方得分相同),则得 1 分。

如果球队输掉了比赛(例如,比对手少进球),就 不得分 。

写出一条SQL语句以查询每个队的 team_id,team_name 和 num_points。

输入


输出

1.查詢三種情況下的host_team,及其得分

sql 复制代码
select host_team ,
case 
	when host_goals > guest_goals then 3 
	when host_goals < guest_goals then 0
	else 1
end as team_goals
from matches;

2.查詢平局的guest_team及其得分

sql 复制代码
select guest_team , 1 as team_goals
from matches
where host_goals = guest_goals;

3.拼接兩種條件下的結果,創建臨時表,統計每個球隊總得分

sql 复制代码
with t1 as (
	select host_team ,
	case 
		when host_goals > guest_goals then 3 
		when host_goals < guest_goals then 0
		else 1
	end as team_goals
	from matches
	union all
	select guest_team , 1 as team_goals
	from matches
	where host_goals = guest_goals
),t2 as (
select host_team,sum(team_goals) goals_sum
from t1
group by host_team
)
select team_id,team_name,coalesce(goals_sum,0) as num_points
from teams left join t2
on teams.team_id =t2.host_team
order by num_points desc,team_id
;
相关推荐
古月居GYH2 小时前
【数据分析】如何在PyCharm中高效配置和使用SQL
ide·sql·pycharm
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
.30-06Springfield5 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
计算机毕设定制辅导-无忧学长6 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
凌肖战7 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
程序员柳7 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
weixin_478689767 小时前
十大排序算法汇总
java·算法·排序算法
梦在深巷、7 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb