經典SQL問題:Top 10%


學生表:

create table hy_student(
   id number(4,0) primary key,
   name nvarchar2(20) not null,
   score number(3,0) not null)

充值:

insert into hy_student
select rownum,dbms_random.string('*',dbms_random.value(1,20)),dbms_random.value(0,100)
from dual
connect by level<201
order by dbms_random.random

第一步把學生按成績逆序排列:

select * from hy_student order by score desc

第二步給加偽列:

select rownum as rn,a.* from (select * from hy_student order by score desc) a

最后就可以檢出前10%的精英了:

select b.* from (select rownum as rn,a.* from (select * from hy_student order by score desc) a) b where b.rn<= (select count(*) from hy_student)/10

結果:

--2020-04-02--

以上用到的全部SQL:

create table hy_student(
   id number(4,0) primary key,
   name nvarchar2(20) not null,
   score number(3,0) not null)
   
insert into hy_student
select rownum,dbms_random.string('*',dbms_random.value(1,20)),dbms_random.value(0,100)
from dual
connect by level<201
order by dbms_random.random

commit;

select * from hy_student order by score desc

select rownum as rn,a.* from (select * from hy_student order by score desc) a

select b.* from (select rownum as rn,a.* from (select * from hy_student order by score desc) a) b where b.rn<= (select count(*) from hy_student)/10

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM