0

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?

Community
  • 1
  • 1
barbaz
  • 1,642
  • 2
  • 17
  • 27

1 Answers1

1

Use a subquery:

SELECT value, (@i := @i + 1) as rank
FROM (SELECT sum(t.value) as value
      FROM table 
      GROUP BY other_field
     ) t CROSS JOIN
     (SELECT @i := 0) rank_init
ORDER BY value DESC;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786