SQL283. 获得积分最多的人(一)
描述
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 |
name | grade_num |
tm | 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');
输出:
tm|4
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3376KB, 提交时间: 2021-12-20
with temp as (select user_id,sum(case when type = 'add' then grade_num else -grade_num end) as grade_sum from grade_info group by user_id order by grade_sum desc) --保证获取最高分数的位置在逆序排序的时候在第一位通过Limit截取 select user.name,temp.grade_sum from temp left join user on temp.user_id = user.id limit 1
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3504KB, 提交时间: 2021-11-30
select t1.name, sum(t2.grade_num) as grade_sum from grade_info t2 left join user t1 on t2.user_id = t1.id where t2.type = 'add' group by t1.name order by sum(t2.grade_num) desc limit 1
Sqlite 解法, 执行用时: 10ms, 内存消耗: 3584KB, 提交时间: 2021-08-10
select user.name,sum(grade_num) as s from user ,grade_info on user.id =grade_info.user_id group by user.id order by s desc limit 1
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3376KB, 提交时间: 2021-09-10
select a.name,b.t from user a join( select user_id ,max(s) as t from( select user_id,sum(grade_num) as s from grade_info group by user_id)) as b on a.id=b.user_id;
Sqlite 解法, 执行用时: 11ms, 内存消耗: 3464KB, 提交时间: 2021-09-19
select m.name,max(m.cnt) from (select u.id,u.name, sum(g.grade_num) as cnt from user u join grade_info g on u.id = g.user_id where g.type='add' group by u.id) m