我有这样的数据:
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_pid
值从未显示在winning_pid
列中,因为pid
值没有赢家,但这些值需要在总计表中。是否有一个快速的解决方案使用
UNNEST()
对吗?我不能这样做:SELECT DISTINCT ON (pair) UNNEST(pair) as pid, COUNT(*) FILTER ( WHERE pid = winning_pid ) AS wins
因为它不识别pid
子句中的FILTER
。我也在想
UNNEST()
不是我想要的,因为我想要一个同时有pid
值和只有一个值的结果表。谢谢!
最佳答案
对切换结果使用并集:
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;
在rextester中测试。
关于postgresql - postgres:取消嵌套数组并计算总数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40566630/