I want to add a rank column indicating the rank of another numerical column in an SQL query using MySQL. For simple, non aggregating queries this can be achieved using a counter variable as follows:
SELECT value, @i:=@i+1 as rank FROM table, (SELECT @i:=0) rank_init ORDER BY value DESC
This was previously described here and elsewhere on SO.
However, if value
is the result of an aggregate function (and the result is therefore ordered by the aggregated values), the rank column seems to be added before the ordering is applied and of course also values are skipped.
SELECT sum(value), @i:=@i+1 as rank FROM table, (SELECT @i:=0) rank_init GROUP BY other_field ORDER BY value DESC
Is there another way without using temporary tables or subqueries?