我想创建一个表NEW_DEPTS。我在DEPARTMENTS表中有DEPARTMENT_ID和DEPARTMENT_NAME。
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语句中不能使用sum,avg,max,min这样的组函数。我需要GROUP BY子句。所以,我想单独解决它。因此,我跳过了“创建表...”声明并写道:
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可以正确运行。
答案 0 :(得分: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
)。