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
;
相关推荐
Q_970956392 分钟前
java+vue+SpringBoo校园失物招领网站(程序+数据库+报告+部署教程+答辩指导)
java·数据库·vue.js
Wyc7240910 分钟前
Maven
java·数据库·maven
军训猫猫头12 分钟前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
程序猿小D13 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
羊小猪~~19 分钟前
数据库学习笔记(十七)--触发器的使用
数据库·人工智能·后端·sql·深度学习·mysql·考研
success25 分钟前
【爆刷力扣-数组】二分查找 及 衍生题型
算法
背太阳的牧羊人1 小时前
Neo4j 的向量搜索(Neo4jVector)和常见的向量数据库(比如 Milvus、Qdrant)之间的区别与联系
数据库·neo4j·milvus
Orlando cron1 小时前
数据结构入门:链表
数据结构·算法·链表
liulun1 小时前
在浏览器中使用SQLite(官方sqlite3.wasm)
数据库·sqlite·wasm
牛客企业服务2 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘