0

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.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
switz
  • 24,384
  • 25
  • 76
  • 101

1 Answers1

3

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):

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228