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

标签 sql postgresql join count

首先,我想为含糊不清的标题道歉(我保证一旦我真正意识到我要解决的问题就会修改它!)

我有两个表,playerma​​tch,如下所示:

玩家:

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

匹配:

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

ma​​tch表中的记录表示两个玩家之间的比赛,其中id列由数据库生成,winner中的值strong> 和 loser 列引用 player 表中的 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;

感谢您的帮助!

最佳答案

尝试

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;

关于sql - PostgreSQL - 选择一列和两列中唯一值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41790841/

相关文章:

mysql - 停止左连接中的数据重复

sql - 如果左连接表中的行为空,则使用另一行

Oracle:通过联合等组合两个group by查询(使用聚合函数count())以获得合并结果

mysql - 如何为我的数据库连接表

mysql - 如何连接三个表以查看所有行

mysql - 如何对另一个表中没有匹配条目的行进行求和?

c# - 在 SQL 或 C# 中对列求和

django - 名称错误 : name 'django_filters' is not defined

hibernate - 我需要在 Maven 依赖项中指定 PostgreSQL 方言吗?

postgresql - 从 CSV 填充 postgres 表列时出现非空约束错误