题解 | #获得积分最多的人(三)#
获得积分最多的人(三)
http://www.nowcoder.com/practice/d2b7e2a305a7499fb310dc82a43820e8
1.type='add'积分为正,否则积分为负,按照user_id计算每个用户的积分和
select user_id,
sum(case when type='add' then grade_num
else -1*grade_num end) sumgrade
from grade_info g
group by user_id
2.使用窗口函数rank()对上表按照积分倒序排序,这样积分最高的用户排序都为1
为方便观看,将步骤1的表记为'user_sum'
select us.user_id,us.sumgrade,rank() over (order by sumgrade) as ranking
from user_id us
3.将步骤2的表记为rank,接下来就是找出rank表中ranking=1的信息并链接user表中的相应信息即可
select u.id,u.name,r.sumgrade as grade_sum
from user u join rank r on u.id=r.user_id
where r.ranking=1
order by u.id
将上述三个步骤整合即为:
select u.id,u.name,rank.sumgrade
from user u
join
(select user_id,sumgrade,rank() over (order by sumgrade desc) as ranking
from
(select user_id,sum(case when type='add' then grade_num else -1*grade_num end) sumgrade
from grade_info g group by user_id))
rank
on u.id=rank.user_id
where rank.ranking=1 order by u.id