使用MYSQL 5.7 的进行分组排序查询的一个简单方案:
方法有2种,
1.利用mysql编程语言特性,采用参数计数实现
2.利用group by ,order by ,leef jion ,count(*) 重构数据去重在排序
表名:test
team | num |
C | 2 |
A | 7 |
B | 7 |
B | 7 |
C | 9 |
A | 2 |
B | 8 |
C | 8 |
A | 4 |
要求 team分组,然后对num排序,
方法一实现
select A.tream,A.num,count(1) rank from test A left join test B on A.tream=B.tream and A.num>=B.num group by A.tream,A.num;
利用join重构数据,按照排序字段,添加关联条件,出现次数,统计出现次数即为排序。
非常不推荐这个方法。
方法二实现
1.添加一个自增序号
定义序号参数@id
select (@id:=@id+1) id,test.* from (select @id:=0) A,test;
2.对分组字段排序,然后在对需要排序字段排序,按照分组字段是否相同添加序号
select (@rank:=CASE WHEN @tmp_tream=B.tream THEN @rank+1 ElSE 1 END) rank,(@tmp_tream=B.tream),B.*
from (select @ranl:=0,@tmp_tream='') A,(select * from test obder by tream,num)B;
3.在构建好的数据上,获取排序
select * from (
select (@rank:=CASE WHEN @tmp_tream=B.tream THEN @rank+1 ElSE 1 END) rank,(@tmp_tream=B.tream),B.*
from (select @ranl:=0,@tmp_tream='') A,(select * from test obder by tream,num) B ) C where C.rank=1;