http://sqlfiddle.com/#!9/cb66d/1
with the following query,
select users.name, race_results.raceid, race_results.place, race_results.winnings
from users
inner join race_results
where race_results.userid = users.id
order by race_results.place asc
I get
**********************************
name | raceid | place | winnings
Bob | 1 | 1 | 1000
John | 3 | 1 | 1000
Bob | 4 | 1 | 1000
Bob | 2 | 1 | 1000
Bob | 5 | 1 | 1000
John | 5 | 2 | 500
Sarah | 3 | 2 | 500
Sarah | 2 | 2 | 500
Sarah | 5 | 3 | 250
John | 2 | 3 | 250
Bob | 3 | 5 | 50
John | 1 | 5 | 50
John | 4 | 5 | 50
Sarah | 1 | 6 | 50
Sarah | 4 | 6 | 50
with the following query,
select users.name, race_results.raceid, race_results.place, race_results.winnings
from users
inner join race_results
where race_results.userid = users.id
and race_results.place = 1
order by race_results.place asc
I get
*********************************
name | raceid | place | winnings
Bob | 1 | 1 | 1000
Bob | 2 | 1 | 1000
John | 3 | 1 | 1000
Bob | 4 | 1 | 1000
Bob | 5 | 1 | 1000
In the game, a user has won if they got first place.
I've tried something like this
select users.name, sum(race_results.winnings) as total_winnings,
count(CASE WHEN race_results.place=1 THEN 1 ELSE 0 END) AS times_won_first_place
from users
inner join race_results
where race_results.userid = users.id
and race_results.place = 1
group by users.id
order by total_winnings desc
I get
**********************************************
name | total_winnings | times_won_first_place
Bob | 4000 | 4
John | 1000 | 1
which is great, but what if this query wasn't primarily for getting how many times a user has one first place and it was just secondary information?
I want something like this
**********************************************
name | total_winnings | times_won_first_place
Bob | 4000 | 4
Sarah | 1350 | 0
John | 1000 | 1
http://sqlfiddle.com/#!9/cb66d/8
Thanks.