使用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 test.tream,test.num,count(1) from test A left jion 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;