我试图解决一个练习,要求我创建一个新专栏,其中包含每个部门员工的平均工资。 我的数据库包含员工和部门表。 员工是一份员工列表,其中包含每个人的薪水及其 department_id 等数据。部门包含 department_id , department_name 等。我已经使用 ALTER TABLE 添加名为 AVG_SALARY 的列进入部门。现在,我想根据员工表中的薪水列填写AVG薪水。到目前为止,我提出了很多解决方案,但都没有奏效。其中一些是:
UPDATE departments D
INNER JOIN employees E ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
SET AVG_SALARY = AVG(employees.SALARY);
GROUP BY DEPARTMENT_ID;
结果:错误代码:1111。无效使用组功能
UPDATE departments D
SET D.AVG_SALARY =
(SELECT AVG(e.SALARY)
FROM employees E INNER JOIN (SELECT * FROM departments) AS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
GROUP BY D.DEPARTMENT_ID);
结果:错误代码:1242。子查询返回超过1行
INSERT INTO departments (DEPARTMENT_ID, AVG_SALARY)
SELECT D.DEPARTMENT_ID, AVG(salary)
FROM EMPLOYEES E INNER JOIN DEPARTMENTS D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
GROUP BY DEPARTMENT_ID;
结果:错误代码:1364。字段' DEPARTMENT_NAME'没有 默认值
任何人都能在这里提供帮助吗?
答案 0 :(得分:0)
尝试使用这个修改后的第二个修改:
UPDATE departments D
SET D.AVG_SALARY =
(SELECT AVG(e.SALARY)
FROM employees E
where D.DEPARTMENT_ID=E.DEPARTMENT_ID
GROUP BY E.DEPARTMENT_ID);