Ora-00935错误组嵌套得太深了

时间:2017-05-28 10:46:56

标签: sql oracle

以下sql查询不断抛出组函数嵌套太深的错误

select department_name 
from department 
where department_id in (select department_id 
                        from student  
                        group by department_id 
                        having count(student_id)=max(count(student_id)));

有人可以建议如何在不制作其他表的情况下纠正这个问题吗?

2 个答案:

答案 0 :(得分:1)

我看不出in买了什么。我发现这更容易编写并遵循from子句中的计算:

select d.department_name
from (select s.department_id, count(*) as num_students,
             rank() over (order by count(*) desc) as seqnum
      from student s
      group by s.department_id
     ) s join
     department d
     on s.department_id = d.department_id
where seqnum = 1;

这也使得在人口最多的部门中增加学生人数变得容易。

答案 1 :(得分:0)

尝试使用MAX分析功能

SELECT department_name 
FROM department 
WHERE department_id IN
  ( SELECT
      department_id
    FROM
      ( SELECT
          department_id,
          COUNT(student_id) students,
          MAX(COUNT(student_id)) OVER () max_students
        FROM student  
        GROUP BY department_id 
      )
    WHERE students=max_students
  );

未经测试。

或者在Oracle 12c以后,您可以使用FECTH子句

SELECT department_name 
FROM department 
WHERE department_id IN
  ( SELECT department_id
    FROM student  
    GROUP BY department_id 
    ORDER BY COUNT(student_id) DESC
    FETCH FIRST ROW WITH TIES
  );