看过之前的博客的应该知道有个曲线救国的方案--忽略

这里发一个基本近似row_number() over(partition by A order by B )的效果

先看效果,懂行的你应该看到玄机了:

mysql 分组排序--进阶版

发出完整sql:

select result.* from (  
select fa_tmp.famc,fa_tmp.jgbm,fa_tmp.khpl,fa_tmp.czsj,@rownum:[email protected]+1 rownum,  
if(@khpl=fa_tmp.khpl and @jgbm=fa_tmp.jgbm ,@rank:[email protected]+1,@rank:=1) as rank,  
@khpl:=fa_tmp.khpl khpl_new ,@jgbm:=fa_tmp.jgbm jgbm_new
from (   
select fa.* from qyjx_khfa_jbxx  fa order by khpl desc, jgbm desc, czsj desc 
) fa_tmp ,(select @rownum :=0 ,@rank:=0, @khpl := null , @jgbm := null ) a ) result

以这个表qyjx_khfa_jbxx  为例,关注红色部分。

order by 排序字段是实际业务分组字段,其他自行理解下!

聪明的小伙伴应该发现一个其实这个更灵活,因为rank是自定义规则,可解决分组条件相同的情况:

比如:薪资相同排名并列的情况,简单介绍核心逻辑

if(@pdept=heyf_tmp.deptid AND @salary>=heyf_tmp.salary,@rank:[email protected]+1,@rank:=1) as rank1, if(@pdept=heyf_tmp.deptid AND @salary=heyf_tmp.salary,@rank:[email protected],@rank) as rank,

用临时rank1过渡,如果相同恢复rank

相关文章:

  • 2022-01-01
  • 2021-07-03
  • 2021-11-26
  • 2021-12-21
  • 2022-12-23
  • 2021-11-19
  • 2022-12-23
  • 2022-01-01
猜你喜欢
  • 2022-12-23
  • 2021-04-04
  • 2021-08-06
  • 2021-12-16
  • 2021-08-29
  • 2022-01-01
相关资源
相似解决方案