首页 > 解决方案 > Oracle“不是按表达式错误-00979 的组”

问题描述

下面是我的 PL/SQL Oracle 代码。它打印最大数量的员工被雇用的年份,并打印该年每个月加入的员工数量。

如果我在没有 for 循环部分的情况下执行以下代码,则会产生错误:

不是按功能分组的错误。

我错过明显的东西的原因是什么?

declare

      v_year  number(4);
      v_c     number(2);
begin
      select  to_char(hire_date,'yyyy') into v_year
      from  employees
      group by to_char(hire_date,'yyyy')
      having count(*) = 
             ( select  max( count(*))
               from  employees
               group by to_char(hire_date,'yyyy')); // gets the year where max employees joined
               
      dbms_output.put_line('Year : ' || v_year);

      for month in 1 .. 12
      loop
          select  count(*) into v_c
          from employees
          where  to_char(hire_date,'mm') = month and to_char(hire_date,'yyyy') = v_year;
          
          dbms_output.put_line('Month : ' || to_char(month) || ' Employees : ' || to_char(v_c));

     end loop;          

end;

下面是没有for循环的代码:

declare

      v_year  number(4);
      v_c     number(2);
begin
      select  to_char(hire_date,'yyyy') into v_year
      from  employees
      group by to_char(hire_date,'yyyy')
      having count(*) = 
             ( select  max( count(*))
               from  employees
               group by to_char(hire_date,'yyyy'));
               
      dbms_output.put_line('Year : ' || v_year);
end;

它会产生以下错误:

错误报告 - ORA-00979:不是 GROUP BY 表达式 ORA-06512:在第 6 行 00979。00000 -“不是 GROUP BY 表达式”
*原因:
*操作:

标签: sqloracleplsqloracle11g

解决方案


为此,您不需要 PL/SQL。此外,如果查询返回多于一行,则您的 SELECT ... INTO 将失败,如果有两年或更多年雇用的最大员工人数相同,则会失败。

select to_char(hire_date, 'YYYY'), to_char(hire_date, 'MM'), count(*)
from employees
group by rollup(to_char(hire_date, 'YYYY'), to_char(hire_date, 'MM'))
having to_char(hire_date, 'YYYY') =
    (select to_char(hire_date, 'YYYY')
       from employees
      group by to_char(hire_date, 'YYYY')
      having count(*) =
         (select max(count(*))
            from employees
           group by to_char(hire_date, 'YYYY')))
order by to_char(hire_date, 'YYYY'), to_char(hire_date, 'MM')

PS 我在 SQL Developer 中运行第二个示例(无循环)时遇到与您相同的错误,但在 SQL*Plus 中运行它时没有收到错误。SQL*Plus 只报告“PL/SQL 过程成功完成”。


推荐阅读