需要用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>
用mysql查询后,怎样生成名次的顺序号SELECT 语句中的 Order By 子句,决定返回记录集合的排序方式
例如:
按照【名次】值,从小到大排序
Select * From 表名 Where ...... Order By 名次
按照【名次】值,从大到小排序
Select * From 表名 Where ...... Order By 名次 Desc
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)