select id, name, grade_num from ( select id, name, grade_num, rank()over(order by grade_num desc) as rk from ( select id, name, sum(if(type='add',grade_num,-1*grade_num)) grade_num from grade_info g left join user u on g.user_id = u.id group by id, name ) t1 ) t2 where t2.rk = 1 order by id
重点:
- 最内层使用如下代码(sum + if),计算每个id的加减后成绩
sum(if(type='add',grade_num,-1*grade_num))
- 次外层使用如下代码(rank窗口函数),赋予所有id的最终成绩排名
rank()over(order by grade_num desc)
- 最外层直接查找即可(筛选条件为where t2.rk = 1)