使用GROUP BY和SUM进行MySQL排名

时间:2013-10-11 13:07:25

标签: mysql

我有一个点表,其中有一些列是:

| 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的排名。

提前感谢您的帮助!

6 个答案:

答案 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 |

这个过程基本上是:

  1. 获取每位用户的总积分数
  2. 按总分排名
  3. 排序
  4. 在获得排名后过滤(否则,排名将受到影响)
  5. 小提琴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