我正在尝试获取psql中两列的总和。
select id as id, name as name, count(winner_id) as winner_count,
(count(winner_id) +count(loser_id)) as total_matches from player left join
matches on matches.winner_id = player.id group by winner_id, player.name,player.id,
matches.loser_id;")
总匹配数应该是matches表中的total或winner_id和loser_id。
但这是不正确的。
它应该为所有玩家返回1个比赛,但对于获胜的球员返回2个比赛,对于失败的球员返回0个比赛。
发布于 2016-11-18 02:18:34
count()
计算值不为NULL
的次数。因此,这两个count()
可能会返回相同的值。我怀疑你想要这样的东西:
select id, name,
sum(case when id = winner_id then 1 else 0 end) as winner_count,
count(m.id) as total_matches
from player p left join
matches m
on m.winner_id = p.id
group by p.name, p.id;
https://stackoverflow.com/questions/40668327
复制相似问题