SQL284. 获得积分最多的人(二)
描述
id | name |
1 | tm |
2 | wwy |
3 | zk |
4 | |
5 | lm |
user_id | grade_num | type |
1 | 3 | add |
2 | 3 | add |
1 | 1 | add |
3 | 3 | add |
4 | 3 | add |
5 | 3 | add |
3 | 1 | add |
id | name | grade_num |
1 | tm | 4 |
3 | zk | 4 |
示例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,'add'), (3,3,'add'), (4,3,'add'), (5,3,'add'), (3,1,'add');
输出:
1|tm|4 3|zk|4
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3496KB, 提交时间: 2021-09-10
select id, name, sum(grade_num) as grade_sum from user inner join grade_info on id=user_id group by id having grade_sum = (select sum(grade_num) as grade_sum from grade_info group by user_id order by grade_sum desc limit 1 ) order by id
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3500KB, 提交时间: 2021-08-09
with zh as( select user_id, sum(grade_num) as total from grade_info group by user_id ) select u.id, u.name, zh.total as grade_sum from user u join zh on zh.user_id = u.id where zh.total = (select max(total) from zh) order by id
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3584KB, 提交时间: 2021-12-05
select id,name,sum(grade_num) as grade_sum from `user` left join grade_info on `user`.id=grade_info.user_id group by id having grade_sum= (select sum(grade_num) r from grade_info g1 group by user_id order by r desc limit 1)
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3456KB, 提交时间: 2021-09-24
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) order by user_id
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3460KB, 提交时间: 2021-09-09
select u.id,u.name,a.s from (select id,s from(select user_id id,sum(grade_num) s from grade_info group by user_id) where s=(select max(s) from (select user_id id,sum(grade_num) s from grade_info group by user_id))) a left join user u on a.id=u.id order by u.id