【问题标题】:Finding Standings Table in a tournament在锦标赛中查找排名表
【发布时间】:2017-05-03 04:58:03
【问题描述】:

我有两张桌子

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);

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

player_id,player_name,total_wins,total_matches

如何进行?

【问题讨论】:

  • 你又做了一个 create table 语句...不清楚你是如何计算总输赢的
  • 你的意思是,你想要一个查询返回一个包含这些列和明显含义的表?

标签: sql postgresql relational-database data-modeling


【解决方案1】:

类似这样的:

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

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2016-09-27
    • 1970-01-01
    • 2020-10-08
    • 2019-03-22
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多