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

2021/4/15 2:25:38

本文主要是介绍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;


这篇关于SQL实战91.获得积分最多的人(三)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程