Postgresql postgres:取消数组的测试并计算总数

Postgresql postgres:取消数组的测试并计算总数,postgresql,Postgresql,我有如下数据: winning_pid losing_pid pair wins 1 2 1,2 7 2 1 1,2 3 3 4 3,4 2 pid opp_pid total wins losses 1 2 10 7 3 2 1 10 3

我有如下数据:

winning_pid  losing_pid  pair  wins
          1           2   1,2     7
          2           1   1,2     3
          3           4   3,4     2
pid  opp_pid  total  wins  losses
  1        2     10     7      3
  2        1     10     3      7
  3        4      2     2      0
  4        3      2     0      2
我想要的结果如下所示:

winning_pid  losing_pid  pair  wins
          1           2   1,2     7
          2           1   1,2     3
          3           4   3,4     2
pid  opp_pid  total  wins  losses
  1        2     10     7      3
  2        1     10     3      7
  3        4      2     2      0
  4        3      2     0      2
基本上是:每个
pid
值和一个对手
pid
值的比赛总数,以及它们之间的总数和输赢。如您所见,在某些情况下,
losing\u pid
值从不显示在
wing\u pid
列中,因为该
pid
值没有赢,但这些值必须在totals表中

是否有一个快速解决方案,可以在配对中使用
UNNEST()
?我不能这样做:

winning_pid  losing_pid  pair  wins
          1           2   1,2     7
          2           1   1,2     3
          3           4   3,4     2
pid  opp_pid  total  wins  losses
  1        2     10     7      3
  2        1     10     3      7
  3        4      2     2      0
  4        3      2     0      2
选择DISTINCT ON(对)UNNEST(对)作为pid,将(*)过滤器(其中pid=WINING_pid)作为wins
计数,因为它不识别
FILTER
子句中的
pid

我还认为
UNNEST()
不是我想要的,因为我想要一个既有
pid
值,又只有一个值的结果表


谢谢

对切换结果使用union:

select
    pid, 
    opp_pid, 
    sum(wins + loses) total,
    sum(wins) wins, 
    sum(loses) loses
from (
    select winning_pid pid, losing_pid opp_pid, wins, 0 loses
    from example
    union
    select losing_pid, winning_pid, 0, wins
    from example
) s
group by 1, 2
order by 1, 2;
测试一下