你必须嵌套另一个级别
select dept_id, stud_count
from (select rownum r, dept_id, stud_count
from (select dept_id, count(*) as stud_count
from TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID
order by stud_count desc)
where rownum <= 2
)
where r = 2;
但是使用 rownum 意味着如果两个或多个记录具有第二个计数,您只会得到一行。所以使用你想要第二高计数的所有行的 dense_rank() 。
select dept_id, stud_count
from (select dept_id, count(*) as stud_count,
dense_rank() over (order by count(*) desc) rnk
from TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID
order by stud_count desc)
where rnk = 2;
例如:
SQL> select dept_id, count(*) stud_count from tbl_student_department_593932 group by dept_id;
DEPT_ STUD_COUNT
----- ----------
Dep03 4 <--
Dep01 3
Dep05 4 <--
Dep02 6
SQL> select dept_id, stud_count
2 from (select rownum r, dept_id, stud_count
3 from (select dept_id, count(*) as stud_count
4 from tbl_student_department_593932
5 group by dept_id
6 order by stud_count desc)
7 where rownum <= 2)
8 where r = 2;
DEPT_ STUD_COUNT
----- ----------
Dep03 4
对比;
SQL> select dept_id, stud_count
2 from (select dept_id, count(*) as stud_count,
3 dense_rank() over(order by count(*) desc) rnk
4 from tbl_student_department_593932
5 group by dept_id
6 order by stud_count desc)
7 where rnk = 2;
DEPT_ STUD_COUNT
----- ----------
Dep03 4
Dep05 4