is there a way in MySQL 4 to select the average of only the best two scores grouped by player from a table storing game details?
DO I need a transaction for this?
CHeers
QatQat
Life is what happens when you are making other plans.
SELECT player_id
, avg(score) as average_score
FROM game_details as X
WHERE 2 >
( SELECT count(*)
FROM game_details
WHERE player_id = X.player_id
AND score > X.score )
GROUP
BY player_id
the subquery now counts how many other rows, for the same player, have a higher score
if the number of rows that have a higher score for the same player is less than 2 (i.e. 1 or 0), then this row X has to be one of the top 2 (i.e. if the count is 0, then X is the highest score for the player, and if the count is 1, then X is the second highest score for the player)
thus the subquery acts as a filter, and ensures we're getting only the top 2 scores per player
the outer query then provides the average per player
I think I've got this. For argument's sake lets say player Dave has the following scores:
18,33,14,27,21,24
and lets say the query checks those rows as X.score in the order they appear here. I know it could be random which row is checked, but hey, it's my scenario.
so X.score=18 is checked and there are four rows with scores greater than it, so it gets discarded.
it would then move on to X.score=33 and find out there are no scores above that so that would be one of the rows that we would use.
It would then step through X.score=14 and discard it for the same reason as X.score=18.
It then steps through to X.score=27 and finds there is only one score greater than it so it must be the second highest score.
So then the scores are 33 and 27 and we now take the average of those two scores to find that Dave has an average score of 30 correct?
So if we wanted the top 3 scores averaged we merely change the 2 > to 3 > in the code above?
then you will have to run a query to get all player scores, sorted into descending score by player, and do the average calculation in your scripting language on the first two rows returned for each player
no prob -- i actually started to write the exact same reply myself (i.e. "just split it into two queries") but luckily i caught myself before i pushed the submit button
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.