来自另一个表的列减去列的总和-SQL select语句

时间:2019-11-07 13:02:42

标签: sql sql-server

https://i.imgur.com/uQWh8NJ.png

我需要有关此SQL语句的帮助。

我不知道如何为子列中的空字段获取null或零 或如何不重复记录。

2 个答案:

答案 0 :(得分:1)

LEFT JOINGROUP BY会有所帮助:

SELECT T1.Emp_Id, T1.Safe_Id, T1.Salary,
       SUM(T2.SubSalary) AS SubSalary,
       (T1.Salary - SUM(T2.SubSalary)) AS [Difference]
FROM TableOne T1
LEFT JOIN TableTwo T2 ON T2.Emp_Id = T1.Emp_Id AND T2.Safe_Id = T1.Safe_Id
GROUP BY T1.Emp_Id, T1.Safe_Id, T1.Salary

答案 1 :(得分:0)

类似的事情应该可以解决问题

 SELECT t1.EmployeeID
    ,t1.safe_id
    ,MAX(t1.salary)
    ,SUM(COALESCE(t2.subSalary, 0)) AS SubSalary
    ,MAX(t1.salary) - SUM(COALESCE(t2.subSalary, 0)) AS difference
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.emp_id = t2.emp_id
    AND t1.safe_id = t2.safe_id
GROUP BY t1.EmployeeID
    ,t1.safe_id