执行SQL报Group function is not allowed但未用分组函数如何解决
报错核心原因
COUNT()属于SQL分组聚合函数,SQL语句的执行顺序中,WHERE子句会在分组、聚合计算之前执行,此时聚合函数的结果还未生成,因此不允许在WHERE条件中直接使用聚合函数,这是你收到报错的根本原因。
修正方案
方案1:使用GROUP BY + HAVING实现过滤
聚合函数的结果过滤需要使用HAVING子句,且需要先对查询的非聚合字段进行分组,修改后的代码如下:
select student.student_id,student.first_name,student.last_name, enrollment.enroll_date from student left outer join Enrollment on student.student_id = enrollment.student_id left join Section on section.section_id = enrollment.section_id left join course on section.course_no = course.course_no where enrollment.enroll_date = TO_DATE('2/15/2007', 'mm/dd/yyyy') group by student.student_id,student.first_name,student.last_name, enrollment.enroll_date having count(course.course_no) = 0;
方案2:使用NOT EXISTS实现(性能更优)
如果你的需求是查询2007年2月15日注册、对应选课没有匹配课程记录的学生,也可以用NOT EXISTS语法实现,执行效率通常比分组聚合更高:
select s.student_id,s.first_name,s.last_name, e.enroll_date from student s join Enrollment e on s.student_id = e.student_id where e.enroll_date = TO_DATE('2/15/2007', 'mm/dd/yyyy') and not exists ( select 1 from Section sec join course c on sec.course_no = c.course_no where sec.section_id = e.section_id );
内容的提问来源于stack exchange,提问作者gnocchi88
相关产品推荐
相关产品推荐

