Question

I'm arranging a sort of Tennis Players database, and I'd like to show each country's top-scoring player. I have the table Players with a column called Country which is the Country the player is from, and a table Rating with a column called Points which is the total number of points the player scored.

Since there are multiple players from each country, I don't know how to show the player with the maximum score from each country.

I tried the following:

select 
   playerstbl.FirstName, playerstbl.Country, ratingtbl.Points 
from 
   playerstbl 
join 
   ratingtbl on playerstbl.PlayerId = ratingtbl.PlayerId
where 
   ratingtbl.Points = (select MAX(ratingtbl.Points) 
                       from ratingtbl 
                       group by playerstbl.Country);
Was it helpful?

Solution

The following query is a somewhat non-intuitive way to answer this question. It is standard SQL though:

select p.FirstName,  p.Country,  r.Points 
from playerstbl p join
     ratingtbl r
     on p.PlayerId = r.PlayerId
where not exists (select 1
                  from playerstbl p2 join
                       ratingtbl r2
                       on p2.PlayerId = r2.PlayerId
                  where p2.Country = p.Country and
                        r2.Points > r.Points
                 );

And, this structure often performs best. It gets the answer to this question: "Get me all players where there is no player in the same country with more points." That is equivalent to getting the max.

For your query to work, you need to incorporate the country into the subquery:

select p.FirstName,  p.Country,  r.Points 
from playerstbl p join
     ratingtbl r
     on p.PlayerId = r.PlayerId
where r.Points = (select MAX(r2.Points)
                  from playerstbl p2 join
                       ratingtbl r2
                       on p2.PlayerId = r2.PlayerI
                  where p2.Country = p.Country
                 );

The where clause in the subquery refers to the outer query. This is called a "correlated subquery" and is a very powerful construct in SQL. Your original query returned an error, no doubt, saying that the subquery returned more than one row. This version fixed that problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top