我有以下代码。
SQL> select * from student_gpa;
SSN GPA
--------------- ----------
22222 3
11111 4
55555 3
33333 4
44444 3
我确实有这个功能来获得前两个gpa得分行。
SQL> select * from(从gpa desc的student_gpa顺序中选择ssn,gpa)其中rownum< = 2;
SSN GPA
--------------- ----------
11111 4
33333 4
我的问题是我使用什么功能来获得GPA得分的前n%。例如,由于我有两个人的GPA为4,密集等级将返回11111占据第1行,22222占据第2行。我实际上正在寻找一个函数,计算5%的GPA得分,返回的值将是11111和22222. 5%的功能不应该仅返回11111。即使我有更多的gpa为4的条目,5%的函数仍会返回所有gpa为4的行。谢谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
前2%选择前30%:
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));
答案 3 :(得分:0)
在Oracle中,这样的前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;