题解 | #获得积分最多的人(三)#

获得积分最多的人(三)

https://www.nowcoder.com/practice/d2b7e2a305a7499fb310dc82a43820e8

思路1

自己想的,复杂版

  • 每个人的分数=sum(add)-sum(reduce)
  • 按照总积分 用窗口函数 添加一列dense_rank
  • 筛选dense_rank()值=1的数据
select 
    t.user_id,
    t.name,
    t.total as grade_num
from 
(
    select 
        distinct g.user_id,
        u.name,
        (ifnull(a.add_num,0) - ifnull(r.re_num,0)) as total,
        dense_rank()over(order by (ifnull(a.add_num,0) - ifnull(r.re_num,0)) desc) as d_rank
    from grade_info g
        left join user u on g.user_id = u.id
        left join (
            select 
                    distinct user_id,
                    sum(grade_num)over(partition by user_id) as add_num
                from grade_info
                where type='add' )a on g.user_id = a.user_id
        left join (
            select 
                    distinct user_id,
                    sum(grade_num)over(partition by user_id) as re_num
                from grade_info
                where type='reduce' )r on g.user_id = r.user_id
                
                )t

where d_rank=1
order by t.user_id asc

思路2

参考评论区,用sum if

select 
    distinct b.user_id,
    u.name,
    b.grade_sum as grade_num
from (
    select
        *,
        dense_rank()over(order by a.grade_sum desc ) as t_rank
    from (
        select 
            user_id,
            sum(if(type='add',grade_num,-1*grade_num))over(partition by user_id) as grade_sum
        from grade_info
    )a
    
) b
left join user u on b.user_id =u.id
where b.t_rank = 1
order by b.user_id asc

全部评论

相关推荐

点赞 评论 收藏
分享
穿件外套出门:这简历一眼太水了,前面有的没的直接删,写项目亮点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务