How to perform grouped ranking in MySQL(如何在 MySQL 中执行分组排名)
                            本文介绍了如何在 MySQL 中执行分组排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
所以我有一个表格如下:
So I have a table as follows:
ID_STUDENT | ID_CLASS | GRADE
-----------------------------
   1       |    1     |  90
   1       |    2     |  80
   2       |    1     |  99
   3       |    1     |  80
   4       |    1     |  70
   5       |    2     |  78
   6       |    2     |  90
   6       |    3     |  50
   7       |    3     |  90
然后我需要对它们进行分组、排序和排序:
I need to then group, sort and order them to give:
ID_STUDENT | ID_CLASS | GRADE | RANK
------------------------------------
    2      |    1     |  99   |  1
    1      |    1     |  90   |  2
    3      |    1     |  80   |  3
    4      |    1     |  70   |  4
    6      |    2     |  90   |  1
    1      |    2     |  80   |  2
    5      |    2     |  78   |  3
    7      |    3     |  90   |  1
    6      |    3     |  50   |  2
现在我知道你可以使用临时变量来进行排名,像这里,但我如何为分组集做这件事?感谢您的任何见解!
Now I know that you can use a temp variable to rank, like here, but how do I do it for a grouped set? Thanks for any insight!
推荐答案
SELECT id_student, id_class, grade,
   @student:=CASE WHEN @class <> id_class THEN 0 ELSE @student+1 END AS rn,
   @class:=id_class AS clset
FROM
  (SELECT @student:= -1) s,
  (SELECT @class:= -1) c,
  (SELECT *
   FROM mytable
   ORDER BY id_class, id_student
  ) t
这很简单:
- 初始查询按 
id_class先排序,id_student第二排序. @student和@class被初始化为-1@class用于测试是否输入了下一组.如果id_class的先前值(存储在@class中)不等于当前值(存储在id_class中),@student被归零.否则递增.@class被赋值为id_class的新值,它将在下一行的第 3 步的测试中使用.
- Initial query is ordered by 
id_classfirst,id_studentsecond. @studentand@classare initialized to-1@classis used to test if the next set is entered. If the previous value of theid_class(which is stored in@class) is not equal to the current value (which is stored inid_class), the@studentis zeroed. Otherwise is is incremented.@classis assigned with the new value ofid_class, and it will be used in test on step 3 at the next row.
这篇关于如何在 MySQL 中执行分组排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 织梦狗教程
				
			本文标题为:如何在 MySQL 中执行分组排名
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
 - 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
 - mysql选择动态行值作为列名,另一列作为值 2021-01-01
 - 什么是 orradiag_<user>文件夹? 2022-01-01
 - 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
 - oracle区分大小写的原因? 2021-01-01
 - 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
 - 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
 - 在多列上分布任意行 2021-01-01
 - MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				