# 求总积分,根据表可知,有增加,有减少,需要将增加总额和减少总额放到同一行,做减法后可得总积分
# 1、积分表 join 用户表,join 结果 id 和 name 分组,利用 case when 求增加总额和减少总额,放到同一行,并相减得出总积分,并利用窗口函数排序总积分,注意,这里已经是分组后的结果,所以 dense_rank 无需再 partition by,直接 order by 即可;
# 2、上一步结果作为子查询,设定好,排名第一,且 id 升序排列,select 出结果



select user_id as id
      ,name
	  ,grade_num
from (
select g.user_id
      ,u.name
      ,sum(case when type='add' then grade_num else 0 end) as add_num
      ,sum(case when type='reduce' then grade_num else 0 end) as reduce_num
      ,sum(case when type='add' then grade_num else 0 end)-sum(case when type='reduce' then grade_num else 0 end) as grade_num
      ,dense_rank() over(order by sum(case when type='add' then grade_num else 0 end)-sum(case when type='reduce' then grade_num else 0 end) desc) as rk
from grade_info as g
left join user as u
on g.user_id=u.id
group by g.user_id
        ,u.name
) as a
where rk=1
order by id