使用MYSQL反转RANK

时间:2014-01-09 13:02:39

标签: mysql rank

我有下表

Member      Date Joined
------      -----------
Alan        01/02/2014
Bob         01/02/2013
Phil        01/02/2012
Bert        01/02/2011

但我想按相反顺序对它们进行排名,同时将结果保留在日期加入订单顺序中。我想输出

No   Member      Date Joined
--   ------      ----------
4    Alan        01/02/2014
3    Bob         01/02/2013 
2    Phil        01/02/2012
1    Bert        01/02/2011

不知道从哪里开始?任何人的想法?

2 个答案:

答案 0 :(得分:1)

您可以在内部查询中使用MySQL的标准“创建行号”例程,然后以相反的顺序从中进行选择:

select
    member,
    date_joined
    rank
from (
    select 
        member,
        date_joined,
        @rank := @rank + 1 as rank
    from 
        members
        join (select @rank := 0) r
    order by 
        date_joined asc
) foo
order by rank desc

答案 1 :(得分:0)

假设您的表格为myTable且其中包含memberdate_joined列,请尝试以下查询:

SELECT * FROM (
  SELECT IF(@prev <> date_joined, @s:=@s+1, @s:=@s) AS `rank`, 
  member, @prev:=date_joined date_joined
  FROM
  myTable, (SELECT @s:= 1, @prev:= 0) s
  ORDER BY date_joined
) t
ORDER BY rank DESC

查询保留计数器变量@s,当date_joined值与先前记录的date_joined值不同时,该变量将递增。