Postgres 嵌套 SQL 查询计数字段

Postgres nested SQL query to count field

我有几张桌子:

users - id

users_matches - user_id, match_id, team

matches - id, winner

我想统计一个用户有多少胜负平局。 team 是一个整数,可以是 1 或 2。winner 也是一个整数,但可以是 1(1 队获胜)、2(2 队获胜)或 3(平局)。

我不确定如何在 Postgres 中混合使用分组 count 和嵌套查询。

假设引用完整性和 Postgres 9.4:

SELECT *, total - wins - ties AS losses
FROM (
   SELECT count(*) AS total
        , count(*) FILTER (WHERE m.winner = um.team) AS wins
        , count(*) FILTER (WHERE m.winner = 3) AS ties
   FROM   users_matches um
   JOIN   matches m ON m.id = um.match_id
   WHERE  um.user_id = 123;  -- for one given user
) sub;

关于聚合 FILTER 子句(随 Postgres 9.4 引入):

  • How can I simplify this game statistics query?