MySql排名用户

时间:2013-09-18 17:01:48

标签: mysql ranking

我正在使用此代码对用户进行排名:

    SELECT @rn:=@rn+1 AS rank, userid, amount
FROM (
  SELECT userid, sum(amount) AS amount
  FROM leads WHERE date(time)='2013-09-15'
  GROUP BY userid
  ORDER BY amount DESC
) t1 , (SELECT @rn:=0) t2;

结果如下:

rank    userid  amount
1         11    1.15
2         10    1.15

即使用户拥有相同金额,也会不断添加排名,任何想法如何解决这个问题?是的,我已经搜索了谷歌和这里的stackoverflow,但我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

首先,你不需要子查询来做你想做的事。

以下是对金额的密集排名,通过引入另一个变量来记住总金额:

SELECT userid, sum(amount) AS amount,
       if(@amount = amount, @rn, @rn := @rn + 1) as ranking,
       @amount := amount
FROM leads cross join
     (select @rn := 0, @amount := -1) const
WHERE date(time) = '2013-09-15'
GROUP BY userid
ORDER BY amount DESC;