我有包含两列的 user_points 表。
根据用户 ID 的计数,从 user_points 中选择 user_values、userid 我想将排名分配给用户..我已经写了这个查询
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;
给出的结果为:
用户名 |总数 |排名
2 6 1
3 2 2
4 2 3
1 1 4
但我想为 userid 3 和 4 assgin 排名 2,因为它们的总数相同..
最佳答案
要模拟 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 |
To emulate DENSE_RANK()
function, which returns the rank of rows within the partition of a result set, without any gaps in the ranking, you can do
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 两个查询的演示
关于mysql - 如果多个用户具有相同的计数值,则分配相同的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20781149/