我有一个点表,其中有一些列是:
| user_id | points |
--------------------
| 1 | 10 |
| 5 | 10 |
| 5 | 50 |
| 3 | 15 |
| 3 | 10 |
我想用MySQL获得每个用户的排名。
我看过这篇文章MySQL get row position in ORDER BY,但它没有SUM,我无法使用SUM。
我希望能够获得给定user_id的排名。
提前感谢您的帮助!
答案 0 :(得分:5)
提醒OP的问题:
我希望能够获得给定user_id的排名。
为了实际执行@rank
上的操作,你必须使用另一个派生表(是的,这是低效的,这就是为什么最好不要在MySQL中处理它):
SELECT * FROM (
SELECT s.*, @rank := @rank + 1 rank FROM (
SELECT user_id, sum(points) TotalPoints FROM t
GROUP BY user_id
) s, (SELECT @rank := 0) init
ORDER BY TotalPoints DESC
) r
WHERE user_id = 3
<强>输出强>
| USER_ID | TOTALPOINTS | RANK |
|---------|-------------|------|
| 3 | 25 | 2 |
这个过程基本上是:
小提琴here。
答案 1 :(得分:3)
试试这个::
SELECT @rownum:=@rownum + 1 as row_number,
t.*
FROM (
select user_id, SUM(points) as Addedpoint
from mytable group by user_id order by Addedpoint desc
) t,
(SELECT @rownum := 0) r
答案 2 :(得分:1)
您可以使用子查询来实现这一目标,在其中您应该计算总和:
SELECT
@rank:=@rank+1 AS rank,
user_id,
total_points
FROM
(SELECT
user_id,
SUM(points) AS total_points
FROM t
GROUP BY
user_id) AS sum_points
CROSS JOIN
(SELECT @rank:=0) AS init
ORDER BY
sum_points.total_points DESC
- 看我的fiddle。
答案 3 :(得分:0)
select
@rownum := @rownum + 1 AS position,
user_id,
total_points
from
(select user_id, sum(points) as total_points from table)a
join
(SELECT @rownum := 0) r
order by total_points desc
答案 4 :(得分:0)
使用用户变量可以执行以下操作: -
SELECT user_id, tot_points, @Rank:=@Rank + 1 AS user_rank
FROM
(
SELECT user_id, SUM(points) AS tot_points
FROM SomeTable
GROUP BY user_id
ORDER BY tot_points DESC
) Sub1
CROSS JOIN (SELECT @Rank:=0) Sub2
答案 5 :(得分:0)
http://sqlfiddle.com/#!2/d0be9/1
SET @rank=0;
select @rank:=@rank+1 AS rank, pointsScored.user_id, sumPoints
from (
select user_id , SUM(points)as sumPoints
from point
group by user_id
order by sumPoints desc
)as pointsScored