Postgres nested SQL query to count field

别等时光非礼了梦想. 提交于 2019-12-13 05:58:59

问题


I have a few tables:

users - id

users_matches - user_id, match_id, team

matches - id, winner

I'd like to count how many wins, losses, and ties a user has. team is an integer that could be 1 or 2. winner is also an integer, but it can be 1 (team 1 wins), 2 (team 2 wins), or 3 (tie).

I'm not sure how to mix a grouped count with a nested query in Postgres.


回答1:


Assuming referential integrity and 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;

About the aggregate FILTER clause (introduced with Postgres 9.4):

  • How can I simplify this game statistics query?


来源:https://stackoverflow.com/questions/31715944/postgres-nested-sql-query-to-count-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!