Postgres嵌套SQL查询以计算字段

时间:2015-07-30 05:44:10

标签: sql postgresql aggregate-functions

我有几张桌子:

users - id

users_matches - user_id, match_id, team

matches - id, winner

我想知道用户有多少胜利,损失和关系。 team是一个整数,可以是1或2. winner也是一个整数,但它可以是1(团队1胜),2(团队2胜)或3(领带)。< / p>

我不确定如何在Postgres中将分组count与嵌套查询混合。

1 个答案:

答案 0 :(得分:2)

假设参照完整性和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引入):