select id , name , grade_num from ( select user_id , sum(real_grade) as grade_num , DENSE_RANK() OVER(ORDER BY SUM(real_grade) DESC) AS rk from ( select user_id , case when type='add' then grade_num when type='reduce' then grade_num * (-1) end as real_grade from grade_info ) t1 group by user_id ) t2 inner join user as u on u.id=t2.user_id where rk=1 order by id asc
!!!嵌套循环