PostgreSQL - 在一列和两列中选择唯一值的计数

时间:2017-01-22 12:23:29

标签: sql postgresql join count

首先,我想为模棱两可的标题道歉(我承诺一旦我意识到我正在努力解决的问题就修改它!)

我有两个表,播放器匹配,如下所示:

播放器:

id name
-- ----
1  John
2  James
3  April
4  Jane
5  Katherine

匹配

id winner loser
-- ------ -----
1  1      2
2  3      4

匹配表中的记录表示两个玩家之间的匹配,数据库生成 id 列,赢家输家列引用播放器表中的 id 列。

我想运行一个查询,它会吐出以下内容:

player.id player.name total_wins total_matches
--------- ----------- ---------- -------------
1         John        1          1
2         James       0          1
3         April       1          1
4         Jane        0          1
5         Katherine   0          0

我目前有一个检索total_wins的查询,但我不确定如何在此基础上获得total_matches数。

select p.id, p.name, count(m.winner)
from player p left join match m on p.id = m.winner
group by p.id, p.name;

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

尝试

select p.id, p.name, 
       sum(case when m.winner = p.id then 1 end ) as total_wins,
       count(m.id) as total_matches
from player p 
left join match m on p.id in ( m.winner, m.loser )
group by p.id, p.name;

答案 1 :(得分:1)

一种方法会拆分match匹配表,因此每次输赢都会有一行。剩下的就是left join和聚合:

select p.id, p.name, coalesce(sum(win), 0) as win, count(m.id) as total_matches
from player p left join
     (select match, winner as id, 1 as win, 0 as loss from match
      union all
      select match, loser as id, 0 as win, 1 as loss from match
     ) m
     on p.id = m.id
group by p.id, p.name;