在 postgresql 中计算赢、平和输的游戏

Calculate won, tie and lost games in postgresql

我有两个 table "matches" 和 "opponents"。

匹配

id | date
---+------------
1  | 2016-03-21 21:00:00
2  | 2016-03-22 09:00:00
...

反对者 (未出场得分为空)

id | match_id | team_id | score
---+----------+---------+------------
1  |  1       |  1      |  0
2  |  1       |  2      |  1
3  |  2       |  3      |  1
4  |  2       |  4      |  1
4  |  3       |  1      |  
4  |  3       |  2      |  
....

目标是创建以下内容table

Team | won | tie | lost | total
-----+-----+-----+------+----------
2    | 1   | 0   | 0    | 1
3    | 0   | 1   | 0    | 1
4    | 0   | 1   | 0    | 1
1    | 0   | 0   | 1    | 1

Postgres v9.5

我该怎么做? (如果有意义的话,我愿意将 "score" 移动到模型中的其他地方。)

我儿子分而治之

with teams as (
    select distinct team_id from opponents
), 
teamgames as (
    select t.team_id, o.match_id, o.score as team_score, oo.score as opponent_score 
    from teams t
    join opponents o on t.team_id = o.team_id
    join opponents oo on (oo.match_id = o.match_id and oo.id != o.id)
),
rankgames as (
    select 
        team_id, 
        case 
            when team_score > opponent_score then 1
            else 0
        end as win,
        case 
            when team_score = opponent_score then 1
            else 0
        end as tie,
        case 
            when team_score < opponent_score then 1
            else 0
        end as loss
    from teamgames
),
rank as (
    select 
        team_id, sum(win) as win, sum(tie) as tie, sum(loss) as loss,
        sum( win * 3 + tie * 1 ) as score
    from rankgames
    group by team_id
    order by score desc
)
select * from rank;

注意 1:您可能不需要第一个 "with",因为您可能已经有一个 table,每个团队有一个记录

注2:我想你也可以通过一次查询得到同样的结果,但是这样步骤更清晰