问题
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