ROW_NUMBER() OVER (PARTITION BY category ORDER BY id) AS idx
含义: 按 category 分组, 组内按 id 排序, 组内排序的序号(行号)作为列 idx
ROW_NUMBER() 在 mysql8 才开始支持, 对于msqyl5.7或对应版本的MariaDB,相同功能的实现可以参考如下 sql
要点:
可以看到,两个结果,在分组变化的地方,idx开始了重新编号,且结果与 ROW_NUMBER() 一致.
需要用row_number来给分组添加序号。
1、创建测试表,插入数据:
create table test(sid int,sname varchar(20),sclass varchar(20),score int) insert into test values (1,'张三','一年一班',100)insert into test values (2,'李四','一年一班',78)insert into test values (3,'王五','一年一班',67)insert into test values (4,'赵六','一年一班',87)insert into test values (5,'badkano','一年二班',98)insert into test values (6,'百度知道团长','一年二班',99)insert into test values (7,'du小小动','一年二班',99)insert into test values (8,'刘备','一年三班',56)insert into test values (9,'张飞','一年三班',67)insert into test values (10,'关羽','一年三班',76)
2、要求按照班级总分给出班级排名(即序号),执行语句:
1select row_number() over (order by score desc) 排名,sclass 班级,score 总分 from (select sclass,SUM(score) score from test group by sclass) t3、查询结果:
mysql>select * from a+-----+
| col |
+-----+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
+-----+
8 rows in set (0.00 sec)
mysql>set @i := 0select @i := @i + 1 as `order`, a.* from a order by col desc
+-------+-----+
| order | col |
+-------+-----+
| 1 | 7 |
| 2 | 6 |
| 3 | 5 |
| 4 | 4 |
| 5 | 3 |
| 6 | 2 |
| 7 | 1 |
| 8 | 0 |
+-------+-----+
8 rows in set (0.00 sec)
mysql>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)