在一个查询

时间:2016-06-24 11:36:47

标签: sql-server tsql sql-insert

Employee表:

ID   EmpName   Salary   DeptID 
------------------------------
 1   'Anil'    10000      1  
 2   'Ram'     15000      2  

Dept表:

ID    DeptName    Salary 
--------------------------
 1    'Accounts' 
 2    'Design' 

上述两个表使用主键 - 外键关系链接。

如何在一个查询(T-SQL)中按部门名称向部门表组中的所有字段插入薪水?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

UPDATE 
    Dept
SET
    Salary = salary_total
FROM    
    (SELECT DeptID, salary_total = SUM(Salary) FROM Employee GROUP BY DeptID) E 
WHERE
    E.DeptID= Dept.ID

答案 1 :(得分:0)

您没有提供足够的信息来测试这一点,但假设您想要对每个部门的薪水求和并更新部门表以反映这应该给您一个启动器;

WITH SalarySum as (
SELECT
    DeptID,
    SUM(Salary) AS SalarySum
FROM Employee 
GROUP BY
    DeptID
)
UPDATE d
SET Salary = s.SalarySum
FROM Dept d
LEFT OUTER JOIN SalarySum s
    on d.ID = s.DeptId