在锦标赛中查找排名表

时间:2016-12-17 16:19:43

标签: sql postgresql relational-database data-modeling

我有2张桌子

create table players
(name text,
 id serial primary key);

create table matches
 (winner integer references players(id),
  loser integer references players(id),
  id serial primary key);

我必须制作一个名为“standings”的表,其中包含:

player_id,player_name,total_wins,total_matches

如何进行?

1 个答案:

答案 0 :(得分:0)

这样的事情:

select p.id, p.name, 
       count(w.id) as total_wins, 
       count(l.id) + count(w.id) as total_matches
from players p 
  left join matches w on w.winner = p.id
  left join matches l on l.loser = p.id
group by p.id, p.name;

在线示例:http://rextester.com/EHDCG19917