使用多个表中的多个值的总和更新列值,每行

时间:2017-08-12 21:24:53

标签: sql sql-server

我正在使用SQL Server并拥有以下3个表:

  1. Employees包含NameSalesBonus1Bonus2
  2. Departments包含NameScore
  3. DepartmentsMembers包含NameEmployees.Name)列,部门(Departments.Name
  4. 如何根据属于该属性的员工的Score + Sales + Bonus1的总和来计算和更新每个部门的Bonus2列的值部?

    编辑:

    根据Ali Adlavaran的回答,我得到了这个查询,以便返回每个部门的结果列表及其计算的Score

    SELECT 
        DepartmentsMembers.Name, SUM(Sales + Bonus1 + Bonus2)
    FROM 
        DepartmentsMembers Department 
    INNER JOIN
        DepartmentsMembers ON Departments.Name = DepartmentsMembers.Name 
    INNER JOIN
        Employees ON DepartmentsMembers.Name = Employees.Name
    WHERE 
        DepartmentsMembers.Name = Departments.Name
    GROUP BY 
        DepartmentsMembers.Name
    

    如何在每个部门的更新声明中加入所有内容?

    谢谢。

2 个答案:

答案 0 :(得分:0)

应该是这样的:

UPDATE Departments
SET Score = 
(
  SELECT SUM(Sales + Bonus1 + Bonus2)
  FROM DepartmentsMembers 
  INNER JOIN Employees ON Employees.Name = DepartmentsMembers.Name
  WHERE DepartmentsMembers.Department =   Departments.Name
  GROUP BY DepartmentsMembers.Department
)

我希望对你有所帮助:)。

答案 1 :(得分:0)

首先,由部门总结:

SELECT dm.Department,
       SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
  FROM DepartmentsMembers dm INNER JOIN
       Employees e
       ON dm.EmployeeName = e.Name
GROUP BY dm.Department;

然后,您可以在部门更新中使用它:

UPDATE d
    SET Score = de.total
    FROM Departments d JOIN
         (SELECT dm.Department,
                 SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
          FROM DepartmentsMembers dm INNER JOIN
               Employees e
               ON dm.EmployeeName = e.Name
          GROUP BY dm.Department
         ) de
         ON de.Department = d.Name;

编辑:

如果您想确保所有部门都得到更新,请使用LEFT JOIN

UPDATE d
    SET Score = COALESCE(de.total, 0)  -- only needed if you don't want `NULL`s
    FROM Departments d LEFT JOIN
         (SELECT dm.Department,
                 SUM(COALESCE(e.Sales, 0) + COALESCE(e.Bonus1, 0) + COALESCE(e.Bonus2, 0)) as total
          FROM DepartmentsMembers dm INNER JOIN
               Employees e
               ON dm.EmployeeName = e.Name
          GROUP BY dm.Department
         ) de
         ON de.Department = d.Name;