PostgreSQL计算总和并使用结果返回获胜者

时间:2017-10-10 18:54:05

标签: sql postgresql

我正在做体育分析(沙滩排球)并得到一张moves的桌子。例如,移动是服务ace,阻止错误或攻击获胜者(由标记标识)。移动可以增加团队a,团队b的分数或保持分数不变。

一些示例moves数据。

set, tag, points_team_a, points_team_b
---,----,--------------,--------------
  1, 520,             1,             0
  1, 510,             0,             0
  1, 300,             0,             1
  1, 410,             0,             0
  1, 620,             0,             0

我有一个查询来返回整体结果。

select
  moves.set,
  sum(moves.points_team_a) as team_a,
  sum(moves.points_team_b) as team_b
from moves
where match_uuid = '26d41fc6-13d3-4af7-a5a3-3ec21bf06f03'
group by set

它显示team_a赢得了第一组21:12和第二组21:18。

set, team_a, team_b
  1,     21,     12
  2,     21,     18

是否可以将整体匹配结果(在本例中为team_a的2:0)添加到查询中?

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

select m.*,
       sum( (team_a > team_b)::int) over (order by set) as running_a_wins,
       sum( (team_b > team_a)::int) over (order by set) as running_b_wins
from (select m.set, sum(m.points_team_a) as team_a, sum(m.points_team_b) as team_b
      from moves m
      where m.match_uuid = '26d41fc6-13d3-4af7-a5a3-3ec21bf06f03'
      group by set
     ) m