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

获得积分最多的人(三)

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值进行排序

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-20 19:57
已编辑
某大厂 golang工程师 23.0k*16.0, 2k房补,年终大概率能拿到
点赞 评论 收藏
分享
点赞 评论 收藏
分享
11-04 14:10
东南大学 Java
_可乐多加冰_:去市公司包卖卡的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务