在mysql中按多个行的总分数对用户进行排名

时间:2016-01-08 17:03:32

标签: mysql

我有与此问题中描述的非常类似的要求。

Rank users in mysql by their points

唯一的区别在于我的数据。上述问题的数据表中每个学生只有一行。但在我的情况下,可能有一个表包含多个行,对于像这样的单个学生

  • 学生1分80
  • 学生2分77.5
  • 学生2分4.5
  • 学生3分77
  • 学生4分77

所以现在排名应该根据用户拥有的SUM点数(总计)来计算。所以在这种情况下结果将是。

  • 学生2等级1,82分
  • 学生1等级2,有80分
  • 学生3等级3,含77分
  • 学生4等级3,含77分

SQL Fiddle for data

我尝试了上述问题的解决方案,但无法得到结果。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

在我之前的回答中使用相同的查询只需更改表学生的子查询,以组合每个学生的所有记录

change [student er]  for 

(SELECT `id`, SUM(`points`) as `points`
 FROM students 
 GROUP BY `id`) er

SQL DEMO

select er.*,
       (@rank := if(@points = points, 
                    @rank, 
                    if(@points := points,    
                       @rank + 1, 
                       @rank + 1                       
                      )
                   )                  
       ) as ranking
from (SELECT `id`, SUM(`points`) as `points`
      FROM students 
      GROUP BY `id`) er cross join
     (select @rank := 0, @points := -1) params
order by points desc;

输出

| id | points | ranking |
|----|--------|---------|
|  5 |     91 |       1 |
|  6 |     81 |       2 |
|  1 |     80 |       3 |
|  2 |     78 |       4 |
|  3 |     78 |       4 |
|  4 |     77 |       5 |
|  7 |     66 |       6 |
|  8 |     15 |       7 |

答案 1 :(得分:3)

试试这个:

select id, points, @row := ifnull(@row, 0) + diff rank
from (select *, ifnull(@prev, 0) != points diff, @prev := points
      from (select id, sum(points) points
            from students
            group by 1
            order by 2 desc) x) y

请参阅SQLFiddle

答案 2 :(得分:1)

EDITED: (这应该有用)

SELECT I.Id, I.Points, Rk.Rank
FROM
(SELECT Id, Points, @Rk := @Rk+1 As Rank
FROM (SELECT id, SUM(points) AS Points
      FROM students
      GROUP BY id
      ORDER BY Points DESC) As T,
      (SELECT @Rk := 0) AS Rk) As I
INNER JOIN
(SELECT * 
FROM (
    SELECT Id, Points, @Rk2 := @Rk2+1 As Rank
    FROM (SELECT id, SUM(points) AS Points
          FROM students
          GROUP BY id
          ORDER BY Points DESC) As T1,
          (SELECT @Rk2 := 0) AS Rk) AS T2
GROUP BY Points) As Rk
USING(Points)

输出将是:

| Id | Points |   Rank  |
|----|--------|---------|
|  5 |     91 |       1 |
|  6 |     81 |       2 |
|  1 |     80 |       3 |
|  2 |     78 |       4 |
|  3 |     78 |       4 |
|  4 |     77 |       6 |
|  7 |     66 |       7 |
|  8 |     15 |       8 |

在第四个位置的两个Ids之后,你将获得第六个位置,因为5个Ids在第六个位置之前。