如果多个用户具有相同的计数值,则分配相同的排名

时间:2013-12-26 07:46:36

标签: mysql

我有两列的user_points表。

从user_points中选择user_values,userid,基于我想为用户分配排名的用户ID的数量..我已经写了这个查询

SELECT count_temp.* ,  @curRank:=(@curRank + 1) AS rank
 FROM (
    SELECT userid, COUNT(*) AS totalcount FROM user_points t GROUP BY t.userid
 ) AS count_temp 
, (SELECT @curRank := 0) r 
ORDER BY totalcount DESC;

将结果显示为:


userid | totalcount |等级


2        6      1
3        2      2
4        2      3
1        1      4

但我想为用户ID 3和4排名2,因为他们的总数相同..

1 个答案:

答案 0 :(得分:3)

要模拟RANK()函数,该函数返回结果集分区中每行的等级,您可以

SELECT userid, totalcount, rank
  FROM
(
  SELECT userid, totalcount, 
         @n := @n + 1, @r := IF(@c = totalcount, @r, @n) rank, @c := totalcount 
    FROM 
  (
    SELECT userid, COUNT(*) AS totalcount 
      FROM user_points t 
     GROUP BY t.userid
     ORDER BY totalcount DESC
  ) t CROSS JOIN 
  (
    SELECT @r := 0, @n := 0, @c := NULL
  ) i
) q;

输出:

| USERID | TOTALCOUNT | RANK |
|--------|------------|------|
|      2 |          6 |    1 |
|      3 |          2 |    2 |
|      4 |          2 |    2 |
|      1 |          1 |    4 |

要模拟DENSE_RANK()函数,该函数返回结果集分区中的行级别,排名没有任何差距,您可以

SELECT userid, totalcount, rank
  FROM
(

  SELECT userid, totalcount, 
         @r := IF(@c = totalcount, @r, @r + 1) rank, @c := totalcount
    FROM 
  (
    SELECT userid, COUNT(*) AS totalcount 
      FROM user_points t 
     GROUP BY t.userid
     ORDER BY totalcount DESC
  ) t CROSS JOIN 
  (
    SELECT @r := 0, @c := NULL
  ) i
) q;

输出:

| USERID | TOTALCOUNT | RANK |
|--------|------------|------|
|      2 |          6 |    1 |
|      3 |          2 |    2 |
|      4 |          2 |    2 |
|      1 |          1 |    3 |

以下是两个查询的 SQLFiddle 演示