sql - How to count two separate columns in the same table and sum them into a new column -


i have 2 tables: playernames , matches.

select * playernames;  id |       name        ----+------------------  38 | abe lincoln  39 | richard nixon  40 | ronald reagan (3 rows)  select * matches;  match_id | winner | loser  ----------+--------+-------         6 |     38 |    39         8 |     38 |    39         9 |     39 |    38        10 |     38 |    39        11 |     40 |    39 (5 rows) 

i need create single query returns 4 columns: id, name, wins, matches. joins , subqueries, can't seem of in 1 query. closest have come execute 2 separate queries. query calculate total wins per player:

select playernames.id, name, count(*) wins  matches, playernames  winner = playernames.id  group playernames.id, winner;  id |       name       | wins  ----+------------------+------  38 | abe lincoln      |    3  39 | richard nixon    |    1  40 | ronald reagan    |    1 (3 rows) 

but have issue separate query if want correctly calculate total number of matches each player:

select playernames.id, name, count(*)  matches, playernames  playernames.id = winner  or playernames.id = loser  group playernames.id;  id |       name       | count  ----+------------------+-------  40 | ronald reagan    |     1  38 | abe lincoln      |     4  39 | richard nixon    |     5 (3 rows) 

i'm avoiding cluttering question many incorrect attempts i've made @ combining these single query. can advise me on how combine these 2 queries one?

i'd use 1 join matches player participated in, , count case expression extract ones won:

select    playernames.id, name,            count(case playernames.id when winner 1 else null end) wins,            count(match_id) matches      playernames  left join matches on playernames.id in (winner, loser) group  playernames.id, name; 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -