Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

oracle - Top n percent top n%

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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           

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...