按用户等级对mysql中的用户排名 [英] Rank users in mysql by their points

查看:216
本文介绍了按用户等级对mysql中的用户排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据我以前计算过的分数对学生进行排名 但是问题是,如果学生有相同的分数,他们应该在同一等级 例如

I am trying to rank my students by their points that I've calculated before but the problem is if students have same points they both should be in same rank E.g

学生1的满分 学生2满分

Student 1 has full points Student 2 has full points

它们都必须排为1;

这是我的数据库示例

Here an example of my database

我要执行的查询是(仅用于选择,然后我可以将值插入到我的列中)

the query I am trying to do is (just for select then I can insert the values to my column)

 SELECT  a.points
        count(b.points)+1 as rank
FROM  examresults a left join examresults b on a.points>b.points
group by  a.points;

编辑以使其更清晰:

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

他们的排名应该像

  • 学生1排名1
  • 学生2排名2
  • 学生3排名2
  • 学生4排名3

我当前的查询返回类似

因为它缺少第三名. (因为第二名有2个值)

As it is missing the third rank. (because second rank has 2 values)

推荐答案

这只是使用变量的Gordon解决方案的修复.问题是您的等级功能不是等级应该起作用的方式. (学生4应该排在第4位)

This is just a fix of Gordon solution using variables. The thing is your rank function isnt the way rank should work. (student 4 should be rank 4)

SQL小提琴演示 您可以添加更多学生来改进测试.

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

输出

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

这篇关于按用户等级对mysql中的用户排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆