先按user_id分组统计和,如下结果:
select user_id,sum(grade_num) as grade_sum from grade_info group by user_id order by grade_sum desc;
因为是最大的只有1个,所以使用limit 1 再联立user表就可以得到结果:
select user.name,t.grade_sum from (select user_id,sum(grade_num) as grade_sum from grade_info group by user_id order by grade_sum desc limit 1) t join user on t.user_id=user.id
也可以用前面学过的sum ()over来解决:
select user.name,t.grade_sum from (select user_id, sum(grade_num)over(partition by user_id ) grade_sum from grade_info order by grade_sum desc limit 1) t join user on t.user_id=user.id