SELECT u.id, u.name, grade_num FROM( SELECT user_id, SUM(t1.real_grade) AS grade_num, DENSE_RANK() OVER(ORDER BY SUM(t1.real_grade) DESC) AS rk FROM( SELECT *, CASE WHEN type = 'add' THEN grade_num WHEN type = 'reduce' THEN (-1) * grade_num END AS real_grade FROM grade_info ) t1 GROUP BY user_id ) t2 JOIN user u ON u.id = t2.user_id WHERE rk = 1 ORDER BY id
一共有三层查询,在最里层的子查询中,使用CASE WHEN语句区分出加的分数和减的分数(real_grade)。在中间一层的查询中,利用上一层的real_grade使用SUM计算总的得分,并且使用窗口函数得到总得分的排序rk。在最外层查询中,利用rk筛选出总得分排名为1的用户。