Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max average for each distinct record in a SQL Query

I have some tables that contain data about players and the games they have bowled this season in a bowling center during their leagues. What this particular query is used for is to sort the top X averages this year for men and for women. I have all of this down, but I still have a problem in some particular case when some players play in multiple leagues and have more than one of their averages in the top X.

Obviously, I only want to list the best average for a given player, so if Player A has the best average with 200 in League ABC and also the second best average with 198 in League DEF, I only want the 200 listed.

Here's a simplified version of the query that I would like to change, because right now I have to remove the duplicates manually or I would have to write a sorter in another language, but I'd rather do it in pure SQL. (I only removed irrelevant information from the query for this example):

SELECT playerId, ROUND(AVG(score),2)Average, season, leagueName, COUNT(score)NumGames FROM Scores
WHERE season = '2011-2012' AND score > -1
GROUP BY season, playerID, leagueName
ORDER BY Average DESC LIMIT 0,30

Basically, the Scores table contains each individual game, a playerId, the season in which the game was played and the leagueName (and other columns that are not required in this example).

The WHERE is to make sure the game was played this season and that the score is positive (-1 is for when people are absent). I group everything by season, playerID and leagueName so I get an average PER LEAGUE for each player instead of an average of all the games played in different leagues.

I tried using the DISTINCT keyword, but that doesn't work because I can't use DISTINCT for only a single column. I also tried other things but none of them came even close to working, so I'm wondering if it's even possible to do this or if I'll have to resort to using another language to sort this result set and removing duplicates?

like image 982
Adam Smith Avatar asked Mar 16 '12 15:03

Adam Smith


1 Answers

You could calculate the average per player per league in a subquery:

select  playerId
,       max(league_avg.score)
from    (
        select  playerId
        ,       avg(score) as score
        from    Scores
        where   season = '2011-2012' 
                and score > -1
        group by
                playerId
        ,       leagueName
        ) as league_avg
group by
        playerId
like image 133
Andomar Avatar answered Oct 14 '22 05:10

Andomar