通关记录一下吧,全部通过,只是个别题写的不够优雅。还是学到了一些东西!
题目点这里
题解:
select
u.id
,u.name
,b.sum_grade_num
from
(
select
user_id
,sum(new_grade_num) as sum_grade_num
,rank() over ( order by sum(new_grade_num) DESC) as t_rank
from
(
select
user_id
,grade_num
,type
,case when type = "add" then grade_num else grade_num*(-1) END AS new_grade_num
from grade_info ) AS a
group by user_id) AS b inner join user AS u
ON b.user_id = u.id
where b.t_rank=1
order by u.id
题解二:
这种解法思路上与上解一致,只是巧妙的运用了if 函数,但if函数并非所有SQL的通用用法。如果以后工作确定使用MySQL 可以再深究一些独有的用法,会让语句更优雅;
select t1.id,t1.name,t0.grade as grade_sum
from(
select user_id,grade,rank()over(order by grade desc) as t
from(
select user_id,sum(if(type='add',grade_num,-1*grade_num)) as grade
from grade_info
group by user_id
) a0
) t0
join user as t1
on t0.user_id = t1.id
where t=1