Here we look at a variety of written and performance comparison of median formation.
1. Data Preparation
DROP table Student;
CREATE TABLE Student
(StuName VARCHAR2(10) NOT NULL,
Subject VARCHAR2(10),
Score INTEGER);
insert into Student values('A1','数学',60);
insert into Student values('A2','数学',90);
insert into Student values ( 'A3', 'English', 80);
insert into Student values ( 'A4', 'English', 40);
insert into Student values ( 'A5', 'mathematics', 70);
insert into Student values('A6','数学',80);
insert into Student values ( 'A7', 'English', 80);
insert into Student values ( 'A8', 'English', 100);
insert into Student values ( 'A9', 'English', 70);
commit;
2. retrieval request
Median formation of each subject,
3.SQL writing and performance comparison
select s1.Subject,s1.Score
from Student s1,Student s2
where s1.Subject=s2.Subject
group by s1.Subject,s1.Score
having sum(case when s1.Score<=s2.Score then 1 else 0 end)>=count(*)/2
and sum(case when s1.Score>=s2.Score then 1 else 0 end) >=count(*)/2;
with tmp as
(select s.SUBJECT
,s.Score
,ROW_NUMBER() over (partition by s.SUBJECT order by s.Score desc) as rn1
,ROW_NUMBER() over (partition by s.SUBJECT order by s.Score asc) as rn2
from Student s)
select distinct t.SUBJECT,t.Score
from tmp t
where t.rn1 in (rn2-1,rn2,rn2+1);
By comparing the above two way analysis function to reduce a table scan, or better performance analysis functions.