列表

详情


SQL282. 最差是第几名(二)

描述

TM小哥和FH小妹在牛客大学若干年后成立了牛客SQL班,班的每个人的综合成绩用A,B,C,D,E表示,90分以上都是A,80~90分都是B,70~80分为C,60~70为D,E为60分以下
假设每个名次最多1个人,比如有2个A,那么必定有1个A是第1名,有1个A是第2名(综合成绩同分也会按照某一门的成绩分先后)。
每次SQL考试完之后,老师会将班级成绩表展示给同学看。
现在有班级成绩表(class_grade)如下:
grade number
A 2
C 4
B 4
D 2
第1行表示成绩为A的学生有2个
.......
最后1行表示成绩为D的学生有2个

老师想知道学生们综合成绩的中位数是什么档位,请你写SQL帮忙查询一下,如果只有1个中位数,输出1个,如果有2个中位数,按grade升序输出,以上例子查询结果如下:
grade
B
C
解析:
总体学生成绩排序如下:A, A, B, B, B, B, C, C, C, C, D, D,总共12个数,取中间的2个,取6,7为:B,C


示例1

输入:

drop table if exists class_grade;
CREATE TABLE class_grade (
grade varchar(32) NOT NULL,
number int(4) NOT NULL
);

INSERT INTO class_grade VALUES
('A',2),
('C',4),
('B',4),
('D',2);

输出:

B
C

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

Sqlite 解法, 执行用时: 10ms, 内存消耗: 3684KB, 提交时间: 2021-08-07

  select g.grade from
  (
  select c.grade,c.number,(
    select sum(number) from class_grade a where c.grade>=a.grade order by a.grade desc) as num1,
     ( select sum(number) from class_grade a where c.grade<=a.grade order by a.grade ) as num2,
    (select sum(number) from class_grade ) allNum
    from class_grade c order by c.grade 
      ) g 
      where g.num1*2>=g.allNum and  g.num2*2>=g.allNum

Sqlite 解法, 执行用时: 11ms, 内存消耗: 3512KB, 提交时间: 2021-09-24

select grade
from
    (select grade,
    (select sum(number) from class_grade) as total,
    sum(number)over(order by grade) a, -- 求正序
    sum(number)over(order by grade desc) b  -- 求逆序
     from class_grade
    order by grade)t
where a >= cast(total as float)/2 and b >= cast(total as float)/2  -- 正序逆序均大于整个数列数字个数的一半
order by grade

Sqlite 解法, 执行用时: 11ms, 内存消耗: 3516KB, 提交时间: 2022-01-27

select grade from (select grade,(select sum(number) from class_grade) as total,
        sum(number) over(order by grade) a,
        sum(number) over(order by grade desc) b
        from class_grade) t1
where a >= total*1.0/2 and b >=total*1.0/2
order by grade;

Sqlite 解法, 执行用时: 11ms, 内存消耗: 3516KB, 提交时间: 2021-09-23

select grade
from (select grade ,sum(number)over(order by grade) cnt1,sum(number)over(order by grade desc) cnt2,
       (select sum(number) from class_grade) totalsnt
     from class_grade)a 
where cnt1>=totalsnt*1.0/2
and cnt2>=totalsnt*1.0/2
order by grade

Sqlite 解法, 执行用时: 11ms, 内存消耗: 3584KB, 提交时间: 2022-02-13

select t.grade from
    (select *,(select sum(number) from class_grade) total,
    sum(number) over (order by grade) a,
    sum(number) over (order by grade desc) b
    from class_grade)t
where t.a>=total*1.0/2 and t.b>= total*1.0/2
order by grade