http://sqlfiddle.com/#!9/cb66d/1
使用以下查询
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
我得到了
**********************************
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
使用以下查询
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
我得到了
*********************************
name | raceid | place | winnings
Bob | 1 | 1 | 1000
Bob | 2 | 1 | 1000
John | 3 | 1 | 1000
Bob | 4 | 1 | 1000
Bob | 5 | 1 | 1000
在游戏中,如果用户获得第一名,他们就赢了。
我尝试过这样的事情
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
我得到了
**********************************************
name | total_winnings | times_won_first_place
Bob | 4000 | 4
John | 1000 | 1
这很好,但是如果这个查询主要不是为了获得用户首先放置多少次而且它只是次要信息呢?
我想要这样的东西
**********************************************
name | total_winnings | times_won_first_place
Bob | 4000 | 4
Sarah | 1350 | 0
John | 1000 | 1
http://sqlfiddle.com/#!9/cb66d/8
感谢。
答案 0 :(得分:1)
SELECT
name
, SUM(winnings) as total_winnings
, SUM(IF(rr.place = 1, 1, 0)) as times_won_first_place
FROM Race_Results rr
JOIN Users u ON (rr.userid = u.id)
GROUP BY userid
ORDER BY total_winnings DESC
如果仅有2个结果,则案例陈述有点矫枉过正。 http://sqlfiddle.com/#!9/cb66d/40
答案 1 :(得分:0)
你走了:
select users.name, sum(race_results.winnings) as total_winnings,
sum(CASE WHEN race_results.place=1 THEN 1 ELSE 0 END) AS
times_won_first_place from users
left join race_results
on race_results.userid = users.id
group by users.id order by total_winnings desc
答案 2 :(得分:0)
这是你需要的。我认为你的测试输出中有一些错误:
select u.name,
sum(r.winnings) as total_winnings,
sum(case when r.place = 1 then 1 else 0 end) as times_won_first_place
from Users u
left join Race_Results r on u.id = r.userid
group by u.id, u.name
输出:
name total_winnings times_won_first_place
Bob 4050 4
John 1850 1
Sarah 1350 0