我想创建一个表 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
所以,我google了一下。我发现像 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
I know that its a "join". But not getting how should I place GROUP BY clause so that my GROUP FUNCTION may run correctly.