我想添加一个排名列,用于指示使用MySQL的SQL查询中另一个数字列的排名。对于简单的非聚合查询,可以使用计数器变量实现,如下所示:
SELECT value, @i:=@i+1 as rank FROM table, (SELECT @i:=0) rank_init ORDER BY value DESC
此前曾在here和其他地方描述过。
但是,如果value
是聚合函数的结果(并且结果因此按聚合值排序),则在应用排序之前似乎添加了rank列,当然也会跳过值
SELECT sum(value), @i:=@i+1 as rank FROM table, (SELECT @i:=0) rank_init GROUP BY other_field ORDER BY value DESC
是否有其他方法不使用临时表或子查询?
答案 0 :(得分:1)
使用子查询:
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;