I need some help on a MySQL SELECT statement. Unfortunately, this statement doesn’t work correctly. It appears to rank based on alphabetical order of the school name instead of reading_percent_proficient_and_advanced. How should I fix it?
SET @rank=0;
SELECT @rank:=@rank+1 as rank,
sy.formatted_school_name,
FLOOR(d.reading_percent_proficient + d.reading_percent_advanced) AS reading_percent_proficient_and_advanced
FROM d_test_scores AS d,
sy_2010_2011_school_type AS sy
WHERE sy.school_id = d.school_id
AND sy.school_group = 'public school'
AND sy.school_type ='elementary'
ORDER BY reading_percent_proficient_and_advanced DESC
If I take out the join, then this statement gives me the correct ranking (but I don’t have the school names then):
SET @rank=0;
SELECT @rank:=@rank+1 as rank,
d.school_id,
FLOOR(d.reading_percent_proficient + d.reading_percent_advanced) AS reading_percent_proficient_and_advanced
FROM d_test_scores AS d
ORDER BY reading_percent_proficient_and_advanced DESC;
What’s the problem with my join?
(Speculation) I believe the rank is being calculated before the ORDER BY ordering is enforced. While in the original query, it just happened that your results came back in the order you wanted before the ORDER BY and thereby the rank was correct, in the advanced query the results are initially coming back in a different order.
Try adding the rank to an already ordered set (subquery) of school name and proficiency ratings.