运行以下sql时,出现“组函数嵌套太深”的信息

时间:2018-07-28 00:49:57

标签: sql oracle join

我知道我在这里遗漏了一些东西,因为我无法在where函数中使用可聚合函数(或在这种情况下,Sum(count ...)中使用双可聚合函数),但似乎无法弄清楚如何重新编写sql。

SELECT city,
       state,
       COUNT(studentID),
       COUNT(instructorID)
FROM   Student
       JOIN Instructor
       ON Student.ZIP= Instructor.ZIP
WHERE  SUM(COUNT(studentID), COUNT(instructorID)) AS TOTAL >= 10
ORDER BY total DESC;

该sql应该列出所有学生和教员加在一起的10个城市。显示城市,州,学生人数,讲师人数以及该城市中的学生/讲师总数。按总数按降序排序。

感谢您能提供的任何帮助...谢谢!

2 个答案:

答案 0 :(得分:2)

如果将聚集函数与非聚集列一起使用,则需要一个GROUP BY子句。您也不能在WHERE子句中定义别​​名,并且如果要过滤聚合函数,则可以使用HAVING子句或在子查询中执行聚合。

类似的东西:

SELECT city,
       state,
       COUNT(studentID),
       COUNT(instructorID)
FROM   Student
       JOIN Instructor
       ON Student.ZIP = Instructor.ZIP
GROUP BY
       city,
       state
HAVING COUNT(studentID) + COUNT(instructorID) >= 10
ORDER BY
       COUNT(studentID) + COUNT(instructorID) DESC;

它没有显示“该城市的学生/教师总数”,但由于这似乎是家庭作业,因此应作为练习来完成。

答案 1 :(得分:0)

您将需要适当的HAVINGGROUP BY子句。不过,更重要的是,您需要正确的查询才能使结果有意义。

假设两个表都具有citystate

select city, state, sum(student) as student, sum(instructor) as instructor
from ((select city, state, 1 as student, 0 as instructor
       from student
      ) union all
      (select city, state, 0 as student, 1 as instructor
       from instructor
      )
     ) si
group by city, state
having sum(student) + sum(instructor) >= 10
order by sum(student) + sum(instructor) desc;

未聚合数据上的join根本不会返回正确的结果。

编辑:

根据评论,正确的查询应为:

select z.city, z.state, sum(si.student) as student, sum(si.instructor) as instructor
from ((select zip, 1 as student, 0 as instructor
       from student
      ) union all
      (select zip, 0 as student, 1 as instructor
       from instructor
      )
     ) si join
     zipcode z
     on z.zip = si.zip
group by z.city, z.state
having sum(ai.student) + sum(si.instructor) >= 10
order by sum(si.student) + sum(si.instructor) desc;