SQL实战91.获得积分最多的人(三)

题目

SQL实战91.获得积分最多的人(三)

解答

with tmp as (
            select a.user_id, a.cnt as add_num ,if(b.cnt is null,0,b.cnt) as reduce_num
            from (select user_id,sum(grade_num) as cnt
                  from grade_info
                  where type = "add"
                  group by user_id ) a
            left join (select user_id,sum(grade_num) as cnt
                       from grade_info
                       where type = "reduce"
                       group by user_id ) b
            on a.user_id = b.user_id )

select c.user_id as id,u.name,c.grade_num
from (select t.user_id,t.grade_num,rank() over (order by t.grade_num desc) as ranking
      from (select user_id,(add_num-reduce_num) as grade_num
            from tmp ) t ) c
left join user as u
on c.user_id = u.id
where c.ranking = 1
order by c.user_id;
上一篇:【数据库修复】.ROGER后缀勒索病毒的数据库.bck文件修复


下一篇:Java基础面试题 91道