错误:ORA-00937
Posted
技术标签:
【中文标题】错误:ORA-00937【英文标题】:Error: ORA-00937 【发布时间】:2013-03-30 04:17:55 【问题描述】:我想创建一个表 NEW_DEPTS。我有 DEPARTMENT_ID 和 DEPARTMENT_NAME,它们位于 DEPARTMENTS 表中。
desc departments
Name Null? Type
------------------------------- -------- ----
DEPARTMENT_ID NOT NULL NUMBER(4)
DEPARTMENT_NAME NOT NULL VARCHAR2(30)
MANAGER_ID NUMBER(6)
LOCATION_ID NUMBER(4)
我的 EMPLOYEES 表包含:
desc employees
Name Null? Type
------------------------------- -------- ----
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
现在,我想创建一个 NEW_DEPTS 表,其中应包含 DEPARTMENT_ID 和 DEPARTMENT_NAME 以及每个部门的总 SALARY。每个部门都有一定数量的员工,因此,对于部门编号 10、20、30 等,应计算总工资。
我的主要查询是:
create table new_depts as
select d.department_id,d.department_name,sum(e.salary) dept_sal
from employees e,departments d
where e.department_id = d.department_id;
我遇到了一个错误:
select d.department_id,d.department_name,sum(e.salary) dept_sal
*
ERROR at line 2:
ORA-00937: not a single-group group function
所以,我用谷歌搜索了它。我发现像 sum、avg、max、min 这样的组函数不能在 select 语句中使用。我需要 GROUP BY 子句。所以,我想单独解决它。因此,我跳过了“create table...”语句并写道:
select distinct d.department_id,d.department_name,sum(e.salary) dept_sal
from employees e,departments d
where e.department_id = d.department_id
group by department_id;
我得到错误:
group by department_id;
*
ERROR at line 4:
ORA-00911: invalid character
然后我写道:
select d.department_id,d.department_name,sum(e.salary) dept_sal
from employees e,departments d
where e.department_id = d.department_id
group by d.department_id;
我收到错误:
select d.department_id,d.department_name,sum(e.salary) dept_sal
*
ERROR at line 1:
ORA-00979: not a GROUP BY expression
然后我写道:
select d.department_id,d.department_name,sum(e.salary) dept_sal
from employees e,departments d
where e.department_id = d.department_id
group by department_id;
我收到错误:
group by department_id
*
ERROR at line 4:
ORA-00918: column ambiguously defined
我知道它是一个“加入”。但不知道我应该如何放置 GROUP BY 子句,以便我的 GROUP FUNCTION 可以正确运行。
【问题讨论】:
GROUP BY department_id
不明确。您需要使用您的表别名。试试GROUP BY d.department_id
。
ORA-00979 not a group by expression 的可能重复项
【参考方案1】:
您需要按不在聚合函数中的所有列进行分组,并且由于您已定义表别名,因此您必须在列中使用该别名。错误ORA-00918: column ambiguously defined
是因为您有两个名为department_id
的列,因此您必须指定department_id
来自的表:
select d.department_id,
d.department_name,
sum(e.salary) dept_sal
from employees e
inner join departments d
on e.department_id = d.department_id
group by d.department_id, d.department_name;
您会注意到我将查询更改为使用 ANSI JOIN 语法 (INNER JOIN
)。
【讨论】:
是的,刚才我用你提到的代码自己解决了这个问题。谢谢。以上是关于错误:ORA-00937的主要内容,如果未能解决你的问题,请参考以下文章
Oracle SQL Developer 案例表达式嵌套查询导致“ORA-00937: not a single-group group function”错误