如何在Mysql中生成排名?

时间:2012-08-01 09:56:48

标签: mysql sql

我在Mysql中有一个复杂的场景。我的表结构和数据如下所示:

Field_a   Field_b   Field_c   Total    Rank
-------   -------   -------   -----    ----
1.2       1.1       3.9       6.2      1
1.2         0         0       1.2      4
1.2       1.1         0       3.3      3
1.2         0       3.9       5.1      2
1.2         0       3.9       5.1      2
1.2         0         0       1.2      4

字段和“Total”和“Rank”不存在,我必须在查询数据库时生成它们。有没有办法在mysql中检索Rank?

此致 Dolendra

3 个答案:

答案 0 :(得分:2)

set @N:=0;
select *,@N:=@N+1 as Rank from
(
select Field_a ,  Field_b ,  Field_c, Field_a  + Field_b +  Field_c  as total 
from table
) as t
order by total desc

答案 1 :(得分:2)

尝试此查询 -

SELECT t1.Field_a + t1.Field_b + t1.Field_c AS total, t2.rank FROM table5 t1
  JOIN (SELECT total, @r:= @r + 1 rank FROM (SELECT Field_a + Field_b + Field_c AS total FROM table5 GROUP BY total DESC) t1, (SELECT @r:=0) t2 ORDER BY total DESC) t2
    ON t1.Field_a + t1.Field_b + t1.Field_c = t2.total

答案 2 :(得分:0)

我认为这就是你要找的东西:

SELECT Field_a, Field_b, Field_c, 
       IF((Field_a + Field_b + Field_c) <> @var_total_prev, 
           (@var_rank:= @var_rank + 1), 
            @var_rank) AS rank,
       (@var_total_prev := (Field_a + Field_b + Field_c)) AS total
FROM my_table a,(SELECT @var_rank := 0, @var_total_prev := 0) r
ORDER BY total DESC;