我写了下面的查询
SELECT DEPT_ID, COUNT(*) AS stud_count FROM TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID ORDER BY stud_count DESC
输出:
DEPT_ID STUD_COUNT
------- ----------
Dep02 5
Dep03 4
Dep01 3
我想选择第二大的stud_count,即4。 所以我使用 rownum 如下
SELECT 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;
但是它不返回任何行,只是空表。我怎么能这样做?
答案 0 :(得分:4)
ROWNUM以特殊方式运行,这就是您需要使用嵌套查询的原因。首先,您将所有数据分组并汇总。在外部查询中,您可以分配行号。在最外面的查询中,您只选择第二行。
SELECT *
FROM
(
SELECT dept_id
, stud_count
, rownum as stud_num
FROM
(
SELECT DEPT_ID
, COUNT(*) AS stud_count
FROM TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID
ORDER BY stud_count DESC
)
)
WHERE stud_num = 2;
如果您熟悉分析功能,则可以改为使用此语句:
SELECT *
FROM
(
SELECT DEPT_ID
, COUNT(*) AS stud_count
, ROW_NUMBER() over (order by COUNT(*) desc) stud_num
FROM TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID
)
WHERE stud_num = 2;
答案 1 :(得分:2)
请检查:
SELECT * FROM
(
SELECT DEPT_ID, COUNT(*) AS stud_count, ROW_NUMBER() over (order by COUNT(*) desc) ROW_NUM
FROM TBL_STUDENT_DEPARTMENT_593932
GROUP BY DEPT_ID
)
WHERE ROW_NUM = 2;
答案 2 :(得分:1)
你必须嵌套另一个级别
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意味着如果两个或多个记录具有第二个计数,则只能获得一行。所以使用你所需要的第二个最高计数的密集的你想要的所有行。
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
答案 3 :(得分:0)
SELECT TOP DEPT_ID, COUNT(*) AS stud_count
FROM TBL_STUDENT_DEPARTMENT_593932 tb1
INNER JOIN tbl_student_department_593932 tb2
ON tb1.dept_id = tb2.dept_id
where tb1.count < tb2.count