问题
I do have the following code.
SQL> select * from student_gpa;
SSN GPA
--------------- ----------
22222 3
11111 4
55555 3
33333 4
44444 3
I do have this function to get the top two gpa score rows.
SQL> select * from (select ssn, gpa from student_gpa order by gpa desc) where rownum <= 2;
SSN GPA
--------------- ----------
11111 4
33333 4
My question is what function do I use to get the top n% of the GPA score. For example, Since I have two individuals with a GPA of 4, dense rank would return 11111 occupying row 1 and 22222 occupying row 2. I was actually looking for a function say that calculates 5% of the GPA score and the returned value would be both 11111 and 22222. The 5% function SHOULD NOT return 11111 only. Even if I had more entries that had gpa of 4, the 5% function would still return all rows that had gpa of 4.Thanks
回答1:
You can try this:
WITH got_analytics AS
(
SELECT ssn, gpa
, ROW_NUMBER () OVER (ORDER BY gpa DESC) AS r_num
, COUNT (*) OVER () AS n_rows
FROM student_gpa
)
SELECT ssn, gpa
FROM got_analytics
WHERE r_num <= ROUND (n_rows * 12/*insert here your n%*/ / 100)
ORDER BY gpa DESC
回答2:
create table student_gpa(ssn number,gpa number);
insert into student_gpa values(1111,4);
insert into student_gpa values(2222,4);
insert into student_gpa values(3333,3);
insert into student_gpa values(4444,2);
select ssn,gpa from(
select ssn, gpa,dense_rank() over (order by gpa desc) rn from student_gpa
)
where rn =1;
ssn gpa
--------------
1111 4
2222 4
回答3:
First 30 percent with 2 selects:
select ssn,gpa from(
select ssn, gpa,rank() over (order by gpa asc) as rn, count(*) over() as cnt
from student_gpa
)
where rn < 0.3*cnt ;
Solution with 4 selects and rownum (very ugly):
select ssn,gpa from(
select ssn, gpa
from student_gpa
)
where rownum < 0.3*(select count(*) from (select ssn, gpa from student_gpa));
回答4:
In Oracle, Top-N Queries like that are usually done using analytic functions, such as NTILE, so in your case:
WITH got_tenth_gpa AS
(
SELECT ssn, gpa
, NTILE (10) OVER (ORDER BY gpa DESC) AS tenth_gpa
FROM student_gpa
)
SELECT ssn, gpa
FROM got_tenth_gpa
WHERE tenth_gpa = 10
ORDER BY gpa DESC;
来源:https://stackoverflow.com/questions/12825196/top-n-percent-top-n