2

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

4

4 回答 4

1

你可以试试这个:

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           
于 2015-04-17T15:10:17.123 回答
0

前 30% 有 2 个选择:

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 ;

具有 4 个选择和 rownum 的解决方案(非常难看):

select ssn,gpa from(
select ssn, gpa
from student_gpa
)
where rownum < 0.3*(select count(*) from (select ssn, gpa from student_gpa));
于 2014-09-30T15:41:38.507 回答
0
 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
于 2012-10-10T17:59:19.720 回答
0

在 Oracle 中,像这样的 Top-N 查询通常使用分析函数完成,例如 NTILE,因此在您的情况下:

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;
于 2016-10-20T09:19:11.177 回答