I'm new to SQL and trying to pick up the basics from an online tutorial. I'm stuck on a query and would appreciate some advice.
Currently, the goal is to create a player standing table for a tournament using queries. I've got two tables; players and matches.
tournament=> select * from players;
id | name
----+------------------
19 | Melpomene Murray
20 | Randy Schwartz
46 | Ricardo
(3 rows)
tournament=> select * from matches;
winner_id | loser_id
-----------+----------
19 | 20
(1 row)
I need to aggregate the wins and matches to do this:
id | name | wins | p_matches
----+------------------+------+-----------
19 | Melpomene Murray | 1 | 1
20 | Randy Schwartz | 0 | 1
46 | Ricardo | 0 | 0
Right now this is my best guess:
tournament=> select players.id, players.name, subq.wins, subq2.p_matches from players,
(select players.id,count(players.id) as wins from players,matches
where matches.winner_id = players.id group by players.id) as subq,
(select count(*) as p_matches from matches) as subq2;
id | name | wins | p_matches
----+------------------+------+-----------
19 | Melpomene Murray | 1 | 1
20 | Randy Schwartz | 1 | 1
46 | Ricardo | 1 | 1
A big chunk of the trouble stems from my subquery. When I run it individually, I'm getting a single row because of the conditional. I'd like to have it listing all ID's with the no-win rows holding zero.
tournament=> select players.id,count(players.id) as wins from players,matches
where matches.winner_id = players.id group by players.id;
id | wins
----+------
19 | 1
I've heard coalesce can do something like this, but I haven't been able to magic it into working. Thoughts?