mysql组内排序
Posted wwwpy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql组内排序相关的知识,希望对你有一定的参考价值。
mysql组内排序
1 创建表和数据
1.1 建库
CREATE DATABASE test;
use test;
1.2 建表
CREATE TABLE `test` (
`class` varchar(10) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL,
`score` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.3 添加数据
# 插入数据
INSERT INTO test VALUES(\'1\',\'a\',2);
INSERT INTO test VALUES(\'1\',\'b\',1);;
INSERT INTO test VALUES(\'1\',\'c\',4);
INSERT INTO test VALUES(\'1\',\'d\',5);
INSERT INTO test VALUES(\'1\',\'e\',7);
INSERT INTO test VALUES(\'1\',\'f\',8);
INSERT INTO test VALUES(\'2\',\'g\',9);
INSERT INTO test VALUES(\'2\',\'h\',0);
INSERT INTO test VALUES(\'2\',\'i\',21);
INSERT INTO test VALUES(\'2\',\'j\',3);
INSERT INTO test VALUES(\'2\',\'k\',4);
INSERT INTO test VALUES(\'2\',\'1\',56);
INSERT INTO test VALUES(\'3\',\'m\',67);
INSERT INTO test VALUES(\'3\',\'n\',89);
INSERT INTO test VALUES(\'3\',\'o\',12);
INSERT INTO test VALUES(\'3\',\'p\',22);
INSERT INTO test VALUES(\'3\',\'q\',23);
INSERT INTO test VALUES(\'3\',\'r\',42);
INSERT INTO test VALUES(\'3\',\'s\',26);
2 组内排序
SELECT a.*,count(1) as rank FROM `test` as a join test as b on a.class=b.class and a.score<=b.score GROUP BY a.class,a.name;
# 核心思想:做同组(同班)的笛卡尔积
# 和自己做连接(条件是班级相同,分数低于同班其他人)
# 然后按班级分组(为了聚合,使用count聚合函数),名字分组(重新打散分组)
# 获取的结果是名字,班级,分数,低于其他人的次数(即分数的名次)
以上是关于mysql组内排序的主要内容,如果未能解决你的问题,请参考以下文章