如果不是列的相同值则递增

时间:2013-12-17 03:44:46

标签: mysql sql sql-order-by

如果排名值不相同,我想增加订单

我尝试过以下查询

SQL FIDDLE

select rank, @rownum := @rownum + 1 AS `myorder`
from myRankorder, (SELECT @rownum := 0) AS a
order by rank desc 

但它会返回此结果

RANK   MYORDER
10     1
8      2
6      3
6      4
4      5
4      6
4      7
3      8
2      9
1      10

期望输出

RANK   MYORDER
10     1
8      2
6      3
6      3
4      4    <-- if rank value is same do not increment myorder value
4      4
4      4
3      5
2      6
1      7

1 个答案:

答案 0 :(得分:2)

有点复杂。您需要一个额外的变量:

select rank,
       if (@prevrank = rank, @rownum, @rownum := @rownum + 1) AS `myorder`,
       @prevrank := rank
from myRankorder cross join
     (SELECT @rownum := 0, @prevrank := -1) const
order by rank desc;

只有一点。 MySQL不保证select中表达式的评估顺序。在实践中,这有效,但不能保证。