別のレベルをネストする必要があります
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を使用するということは、2つ以上のレコードに2番目のカウントがある場合、1行しか取得できないことを意味します。したがって、2番目に多いカウントのすべての行が必要な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
vs;
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