sql - 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 表达式”
*原因:
*操作:
解决方案
为此,您不需要 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 过程成功完成”。
推荐阅读
- java - 约束集不起作用
- mysql - 使用基于“类型”的变量存储 MySQL 对象
- python - 一次在 Pandas 中重新编码多个变量
- ios - UITableview 里面的 UICollectionView,table 应该显示动态值,没有固定值。如何生成这个?
- ionic-framework - 离子:package.json 缺少启动脚本
- python-3.x - 如何使用python和selenium动态获取网页中触发的标签
- yii2 - Yii2客户端验证刷新表单提交页面
- java - 如何在没有 Sonarqube 问题的情况下在 spring 中自动连接静态字段?
- ajax - AJAX成功的Django渲染模板
- pandas - 熊猫适用于索引