我有两张桌子。
表1:由球员姓名及其身份组成。
tournament=> select * from Players;
id | name
----+--------
1 | Rahul
2 | Rohit
3 | Ramesh
4 | Roshan
5 | Ryan
6 | Romelu
7 | Roman
8 | Rampu
(8 rows)
表2:由对手互相比赛组成,第1列包含获胜者的名字和第2栏输家。所以这意味着他们都参加了比赛。
tournament=> select * from Matches;
id | winner | loser
----+--------+-------
1 | 1 | 2
2 | 3 | 4
3 | 5 | 6
4 | 7 | 8
(4 rows)
现在我想计算不同玩家所玩的比赛数量,我已经通过以下查询计算了玩家赢得的比赛数量。
SELECT Players.id, COUNT(Matches.winner) AS Points FROM Players LEFT JOIN (SELECT * from Matches) AS Matches ON Players.id = Matches.winner GROUP by Players.id Order by Points desc, Players.id;
id | points
----+---
1 | 1
3 | 1
5 | 1
7 | 1
2 | 0
4 | 0
6 | 0
8 | 0
(8 rows)
但是我无法弄清楚我应该如何计算每个球员所打的比赛数?
从匹配表中我们可以看到每个玩家都玩了一次,但是我无法在psql中写这个。
答案 0 :(得分:1)
需要一个简单的嵌套子查询,如下所示:
SELECT pl.id,
(
SELECT COUNT(id)
FROM Matches
WHERE winner = pl.id OR loser = pl.id
) AS matches
FROM Players pl
答案 1 :(得分:0)
以下查询在两个单独的查询中计算赢家和输家ID值,然后UNION
编辑在一起。没有重复计算的担心,因为一支球队无法对抗自己,而只能与另一支独特的球队对抗。外部查询总结了团队数量。
SELECT t.id, COUNT(t.id) AS numMatches FROM (
SELECT winner AS id FROM Matches UNION ALL
SELECT loser AS id FROM Matches
) t GROUP BY t.id