如何使用表中的3个连接更新数据?

时间:2018-06-05 09:46:04

标签: sql sql-server database sql-server-2008

我有一项任务要做:使用以下条件更新表commission_pct中的Employees(取决于表Departments):注意 - 最大工资可以从表作业获得。

部门名称 - commission_pct

  • 管理 - Max_Salary * 5%

  • 营销 - Max_Salary * 10%

  • 采购 - Max_Salary * 15%
  • 财务 - Max_Salary * 25%
  • 送货 - Max_Salary * 15%
  • IT - Max_Salary * 25%

这是EMPLOYEES表:

enter image description here

这是DEPARTMENTS表:

enter image description here

这是JOBS表:

enter image description here

我已经写了这个查询:

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

,此查询的结果如下所示:

enter image description here

我不知道如何更新它,我对如何更新特定部门感到困惑。

2 个答案:

答案 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

这将留下NULLJOB_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;