I'm trying to fetch statistics to an user for a game application but need help with making it to work with out having to make more then one query.
This is how it looks at the moment in short: Table: userid(X int), outcome(win and loss), race (A, B and C)
I need now to fetch the count of win and loss for each race:
Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = A
Select count(outcome) as loss from games where userid = X and outcome = 'loss' AND race = A
Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = B
Select count(outcome) as loss from games where userid = X and outcome = 'loss' AND race = B
Select count(outcome) as win from games where userid = X and outcome = 'win' AND race = C
Select count(outcome) as loss from games where userid 开发者_如何学C= X and outcome = 'loss' AND race = C
Then i basically calculates them in php after that but this is ridiculously slow approach when a large number of games is in the database.
So i basically want to have an query that groups by race like this:
Race | Win | Loss
A_____x_____x
B_____x_____x
C_____x_____x
I'm quite new to more complex forms of SQL so any suggestions on optimize this query would be helpful.
Thank you.
SELECT race,
COUNT(CASE
WHEN outcome = 'win' THEN 1
END) AS win,
COUNT(CASE
WHEN outcome = 'loss' THEN 1
END) AS loss
FROM games
WHERE userid = X
AND race IN ( 'A', 'B', 'C' )
GROUP BY race
精彩评论