[英]Calculating the win/loss ratio per team
I have the following two tables:我有以下两个表:
sport_a_statistics: sport_a_statistics:
id team_id game_id points
1 1 1 7
2 2 1 8
3 3 2 6
4 1 2 9
sport_b_statistics: sport_b_statistics:
id team_id game_id points
1 1 3 2
2 2 3 1
3 3 4 3
4 1 4 10
I want to calculate the win/loss ratio for each team.我想计算每支球队的胜负比。 This includes making sure to capture the wins and losses from both sport tables since my tournament involves 2 sports.这包括确保从两个运动表中记录输赢,因为我的比赛涉及两项运动。 So the output I'm looking for is the following:所以我正在寻找的 output 如下:
team_id wins loss ratio
1 3 1 3.0
2 1 1 1.0
3 0 2 0.0
I can't wrap my head around how I would do this in one query.我无法理解如何在一个查询中执行此操作。
Assuming you have no ties, you can use window functions and union all
:假设您没有联系,您可以使用 window 函数并union all
:
select team_id,
sum(points = max_points) as num_wins,
sum(points < max_points) as num_losses,
sum(points = max_points) / nullif(sum(points < max_points), 0) as ratio
from ((select a.*, max(points) over (partition by game_id) as max_points
from sport_a a
) union all
(select b.*, max(points) over (partition by game_id) as max_points
from sport_b b
)
) ab
group by team_id
Made a small edit ^做了一个小编辑^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.