2

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

    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 上搜索了谷歌和这里,但我无法解决这个问题。

4

1 回答 1

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;
于 2013-09-18T17:07:31.780 回答