简体   繁体   English

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

[英]Sum of column minus column from another table - SQL select statement

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

I need help with this SQL statement.我需要有关此 SQL 声明的帮助。

I don't know how to get a null or zero for empty fields in subsalary column or how not to duplicate the records.我不知道如何获得 null 或零作为副工资列中的空字段或如何不复制记录。

LEFT JOIN with GROUP BY will help:使用GROUP BYLEFT JOIN将有助于:

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

something like this should do the trick像这样的东西应该可以解决问题

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SQL根据另一个Select语句从表中选择列 - SQL Select Column From Table Based on Another Select Statement 从SQL中的另一个表中选择一个列和值的SUM() - SELECT a column and SUM() of values from another table in SQL SQL从一个表列中选择一个最小值,然后将结果插入一个SQL语句的另一个表列中 - Sql Select a minimum value from a table column and insert the results in another table column in one SQL statement SQL通过联结表从其他表中选择总和作为列 - SQL select sum from other table as a column via junction table Function 将从 SQL 表中获取 select 值并根据另一列值进行求和 - Function that will select value from SQL table and do a sum based on another column value SQL求和字段并选择一列(有条件)并求和另一列 - SQL sum field and select a column (with condition) and sum another column Oracle SQL select 一个表列的最终值类似于其他表列中包含值负 1 位的值 - Oracle SQL select final value of one table column like value from other table column that contains value minus 1 digit SQL:在另一个表的列中选择一列 - SQL: Select One column into a column in another table 从一个表中返回 SUM(column) 和从另一个表中返回 SUM(column) - Return SUM(column) from a table and SUM(column) from another table SQL 通过ID从另一个表中获取列的总和 - SQL Get sum of a column from another table by ID
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM