2

我在 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

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

问候多伦德拉

4

3 回答 3

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
于 2012-08-01T10:15:39.940 回答
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
于 2012-08-01T10:01:50.483 回答
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;
于 2012-08-01T10:06:28.250 回答