我有一项任务要做:使用以下条件更新表commission_pct
中的Employees
(取决于表Departments
):注意 - 最大工资可以从表作业获得。
部门名称 - commission_pct
管理 - Max_Salary * 5%
营销 - Max_Salary * 10%
这是EMPLOYEES
表:
这是DEPARTMENTS
表:
这是JOBS
表:
我已经写了这个查询:
SELECT
DEPARTMENTS.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME,
JOBS.MAX_SALARY
FROM
EMPLOYEES
INNER JOIN
DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
INNER JOIN
JOBS ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
AND DEPARTMENT_NAME IN ('Administration', 'Marketing',
'Purchasing', 'Finance',
'Shipping', 'IT')
GROUP BY
DEPARTMENTS.DEPARTMENT_NAME, DEPARTMENTS.DEPARTMENT_ID, JOBS.MAX_SALARY
,此查询的结果如下所示:
我不知道如何更新它,我对如何更新特定部门感到困惑。
答案 0 :(得分:0)
您需要使用update
运行inner join
语句,如下所示:
update e
set commission_pct =
case when d.DEPARMENT_NAME = 'Administration' THEN j.MAX_SALARY * 0.05
when d.DEPARMENT_NAME = 'Marketing' THEN j.MAX_SALARY * 0.1
when d.DEPARMENT_NAME = 'Purchasing' THEN j.MAX_SALARY * 0.15
when d.DEPARMENT_NAME = 'Finance' THEN j.MAX_SALARY * 0.25
when d.DEPARMENT_NAME = 'Shipping' THEN j.MAX_SALARY * 0.15
when d.DEPARMENT_NAME = 'IT' THEN j.MAX_SALARY * 0.25
else 0
end
from Employees as e
inner join department as d on e.DEPARTMENT_ID = d.DEPARTMENT_ID
inner join jobs as j on e.JOB_ID = j.JOB_ID
这将留下NULL
,JOB_ID
表中未列出员工JOBS
。
答案 1 :(得分:0)
由于聚合,更新查询看起来有点不同。您需要在子查询或CTE中处理它:
update j
set min_salary = ed.min_salary,
max_salary = ed.max_salary
from jobs j join
(select e.job_id, min(e.salary) as min_salary, max(e.salary) as max_salary
from employees e join
departments d
on d.department_id = e.department_id
where d.department_name in ('Administration', 'Marketing', 'Purchasing',
'Finance', 'Shipping', 'IT'
)
group by e.job_id
) ed;