题解 | #获得积分最多的人(三)#
获得积分最多的人(三)
http://www.nowcoder.com/practice/d2b7e2a305a7499fb310dc82a43820e8
SELECT b.user_id id, u.name, b.grade_num FROM user u JOIN ( SELECT a.user_id, SUM(a.new_grade_number) grade_num, RANK()OVER(ORDER BY SUM(a.new_grade_number) DESC) grade_rank FROM ( SELECT user_id, CASE WHEN type = "reduce" THEN -grade_num ELSE grade_num END new_grade_number FROM grade_info ) a GROUP BY a.user_id ) b ON b.user_id = u.id WHERE b.grade_rank = 1 ORDER BY b.user_id
1. 先用case when生成一个表a,具有两列:user_id, 带负数的number
2. 再生成一个表b,具有三列:user_id, sum(number),sum(number)的排名
3. 简单join上带有name的表
这样的好处是层次清晰,个人觉得方便调试,一层一层来