如何查找玩家所玩的比赛数量?

时间:2017-03-18 22:37:00

标签: postgresql

我有两张表matchplayer。我想通过添加no_of_winsno_of_loses列来查找每个玩家所玩的匹配总数。

player

 id | name   
----|----
  1 | Suhas
  2 | Srivats
  3 | James
  4 | Watson

match

 id | winner | loser 
----|--------|-------
  1 |      1 |     2
  2 |      1 |     3
  3 |      1 |     4
  4 |      2 |     4
  5 |      4 |     3
  6 |      3 |     2

我尝试了以下SQL命令:

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

此命令显示丢失数量的错误输出。

 id |  name   | no_of_wins | no_of_loses 
----|---------|------------|-------------
  1 | Suhas   |          3 |           3
  2 | Srivats |          1 |           1
  3 | James   |          1 |           1
  4 | Watson  |          1 |           1

请帮助。

2 个答案:

答案 0 :(得分:1)

您的查询会导致错误,因为您没有将p.name添加到GROUP BY子句中。

您必须加入match两次,因为这是两个独立的联接:

SELECT p.id,
       p.name,
       COALESCE(w.wins, 0) no_of_wins,
       COALESCE(l.losses, 0) no_of_losses
FROM player p
   LEFT JOIN
      (SELECT winner id,
              count(*) wins
       FROM match
       GROUP BY winner
      ) w
      USING (id)
   LEFT JOIN
      (SELECT loser id,
              count(*) losses
       FROM match
       GROUP BY loser
      ) l
      USING (id);

答案 1 :(得分:1)

计算两个查询中玩家的胜负总数,并(完整)按玩家ID加入:

select 
    name, 
    coalesce(wins, 0) as no_of_wins, 
    coalesce(loses, 0) as no_of_loses,
    coalesce(wins, 0) + coalesce(loses, 0) as total
from (
    select winner as id, count(*) as wins
    from match
    group by 1
    ) w
full join (
    select loser as id, count(*) as loses
    from match
    group by 1
    ) l using (id)
full join player using(id)
order by id;

  name   | no_of_wins | no_of_loses | total 
---------+------------+-------------+-------
 Suhas   |          3 |           0 |     3
 Srivats |          1 |           2 |     3
 James   |          1 |           2 |     3
 Watson  |          1 |           2 |     3
(4 rows)