我是 SQL 的新手,正在尝试从在线教程中学习基础知识。我被困在查询中,希望得到一些建议。
目前,目标是使用查询为锦标赛创建玩家站立表。我有两张 table ;球员和比赛。
tournament=> select * from players;
id | name
----+------------------
19 | Melpomene Murray
20 | Randy Schwartz
46 | Ricardo
(3 rows)
tournament=> select * from matches;
winner_id | loser_id
-----------+----------
19 | 20
(1 row)
我需要汇总胜利和比赛来做到这一点:
id | name | wins | p_matches
----+------------------+------+-----------
19 | Melpomene Murray | 1 | 1
20 | Randy Schwartz | 0 | 1
46 | Ricardo | 0 | 0
现在这是我最好的猜测:
tournament=> select players.id, players.name, subq.wins, subq2.p_matches from players,
(select players.id,count(players.id) as wins from players,matches
where matches.winner_id = players.id group by players.id) as subq,
(select count(*) as p_matches from matches) as subq2;
id | name | wins | p_matches
----+------------------+------+-----------
19 | Melpomene Murray | 1 | 1
20 | Randy Schwartz | 1 | 1
46 | Ricardo | 1 | 1
很大一部分问题源于我的子查询。当我单独运行它时,由于有条件,我得到了一行。我想让它列出所有 ID,其中不赢的行为零。
tournament=> select players.id,count(players.id) as wins from players,matches
where matches.winner_id = players.id group by players.id;
id | wins
----+------
19 | 1
我听说 coalesce 可以做这样的事情,但我一直无法让它发挥作用。想法?
最佳答案
还有这个,我不确定哪个性能更好(可能比多个子查询更好)。
select p.id,
p.name,
count(case when m.winner_id = p.id then 1 end) won,
count(m.*) total
from players p
left join matches m
on m.winner_id = p.id
or p.id = m.loser_id
group by p.id, p.name;
这会选择所有玩家记录,并左连接 matches 表(无论该玩家 id 是否存在于其中),然后对结果进行分组,在这种情况下可以使用诸如计数之类的聚合函数。
第一个计数聚合函数将只计算 winners 列中具有玩家 ID 的行(获胜者),第二个聚合函数将计算它们是否在任一列中。
关于sql - 带默认值的 PostgreSQL 查询数据聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44142146/