SQL285. 获得积分最多的人(三)
描述
id | name |
1 | tm |
2 | wwy |
3 | zk |
4 | |
5 | lm |
user_id | grade_num | type |
1 | 3 | add |
2 | 3 | add |
1 | 1 | reduce |
3 | 3 | add |
4 | 3 | add |
5 | 3 | add |
3 | 1 | reduce |
id | name | grade_num |
2 | wwy | 3 |
4 | 3 | |
5 | lm | 3 |
示例1
输入:
drop table if exists user; drop table if exists grade_info; CREATE TABLE user ( id int(4) NOT NULL, name varchar(32) NOT NULL ); CREATE TABLE grade_info ( user_id int(4) NOT NULL, grade_num int(4) NOT NULL, type varchar(32) NOT NULL ); INSERT INTO user VALUES (1,'tm'), (2,'wwy'), (3,'zk'), (4,'qq'), (5,'lm'); INSERT INTO grade_info VALUES (1,3,'add'), (2,3,'add'), (1,1,'reduce'), (3,3,'add'), (4,3,'add'), (5,3,'add'), (3,1,'reduce');
输出:
2|wwy|3 4|qq|3 5|lm|3
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3588KB, 提交时间: 2021-11-30
with C as(with B as(with A as(select user_id, (case when type='add'then grade_num else-1*grade_num end) as grade_num from grade_info) select user_id,sum(grade_num) as num from A group by user_id) select user_id,num,dense_rank() over(order by num desc) t_rank from B) select id,name,num from C left join user D on C.user_id=D.id where t_rank=1 order by id
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3388KB, 提交时间: 2021-12-12
with new as ( select user_id, sum(case when type = 'add' then grade_num else grade_num*(-1) end) as grade_sum from grade_info group by user_id ) select user_id, name, grade_sum from new as n left join user as u on n.user_id = u.id where grade_sum=(select max(grade_sum) from new)
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3456KB, 提交时间: 2022-02-04
select user.id,user.name,a.grade_sum from ( select user_id,sum(grade_sum) as grade_sum from ( select user_id, case when type='add' then sum(grade_num) when type ='reduce' then sum(-grade_num) end as grade_sum from grade_info group by user_id,type )group by user_id ) a left join user on a.user_id = user.id where a.grade_sum = ( select max(grade_sum) from ( select user_id,sum(grade_sum) as grade_sum from ( select user_id, case when type='add' then sum(grade_num) when type ='reduce' then sum(-grade_num) end as grade_sum from grade_info group by user_id,type )group by user_id ) )
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3456KB, 提交时间: 2021-09-01
with new as ( select user_id, sum( case when type='add' then grade_num else (-1)*grade_num end ) as grade_sum from grade_info group by user_id ) select user_id, name, grade_sum from new left join user as u on new.user_id=u.id where grade_sum=(select max(grade_sum) from new)
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3460KB, 提交时间: 2021-09-02
with new as( select user_id, sum( case when type="add" then grade_num else grade_num*(-1) end ) as grade_sum from grade_info group by user_id ) select id ,name ,grade_sum from new n left join user u on u.id=n.user_id where grade_sum=(select max(grade_sum) from new)