计算每个团队的胜负率

xzabzqsa  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(274)

我有以下两张table:
体育统计:

id      team_id     game_id     points
1       1           1           7   
2       2           1           8
3       3           2           6   
4       1           2           9

体育统计:

id      team_id     game_id     points
1       1           3           2   
2       2           3           1
3       3           4           3   
4       1           4           10

我要计算每个队的胜负比。这包括确保从两个运动表中记录胜负,因为我的比赛涉及两个运动。所以我想要的结果如下:

team_id    wins    loss    ratio
1          3       1       3.0
2          1       1       1.0
3          0       2       0.0

我无法用一个查询来概括我将如何做到这一点。

afdcj2ne

afdcj2ne1#

假设没有关系,可以使用窗口函数和 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

做了一个小编辑^

相关问题