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

获得积分最多的人(三)

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

select user.id,user.name,f.s_n from user,
(select user_id, sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id) f where user.id=f.user_id and f.s_n=

(select sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id order by s_n desc limit 1)

order by f.user_id 

思路:

1.将type中reduce和add进行分类,并改变grade_num的值(add变为正,reduce变为负)

select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id

2.求出grade——info表中中各个user_id的sum

select user_id, sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id

3.求出最大值,在第二部基础上对sum值进行降序排序,并取第一个值

select sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id order by s_n desc limit 1

4.通过where条件将两个表合并,并求出sum值等于第三步求出的最大值即可

select user.id,user.name,f.s_n from user,
(select user_id, sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id) f where user.id=f.user_id and f.s_n=

(select sum(real_value) s_n from 
(select user_id ,if(type='reduce',-grade_num,grade_num) real_value from grade_info) g 
group by user_id order by s_n desc limit 1)

order by f.user_id 

其他思路,可以通过窗口函数对sum值进行排序

全部评论

相关推荐

牛客737698141号:他们可以看到在线简历的。。。估计不合适直接就拒了
点赞 评论 收藏
分享
11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务