SQL从两个不同的表中添加和减去数据

时间:2016-04-03 05:09:05

标签: mysql sql ms-access

我是SQL新手,这是我生命中的第一个SQL程序。我想制作一个包含以下内容的程序:

  1. 一张表,其中记录了客户在一周内交付的货物数量,每个货物交付的费率(费用),发货费用。
  2. 另一张持有费用的表格,例如燃油,保险,拖车租金等。
  3. 我需要获得客户所有费用的总和,以及所有费率的总和(每次负载的挣钱),然后从每个客户的总净支付中减去总费用。
  4. 注意:

    QuickPay= Rate*0.05
    NetPay=Rate-(DispatchFee+QuickPay),
    TotalExpenses= Fuel+Advance+Insurance+Trailer
    FinalPay=NetPay-TotalExpenses
    

    我为每个表创建了一个查询,以进行计算,但我需要将所有查询组合在一起。以下是查询的代码:

    查询TblLInfo

    SELECT CustName, sum(Rate) AS RateFee, sum(Disp_Fee) AS DispFee, sum(Rate*0.05) AS QuickPay, sum((Rate)-((Rate*0.05)+(Disp_Fee))) AS NetPay
    FROM TblLInfo
    GROUP BY CustName;
    

    查询TblExp

    SELECT CustName, sum(Fuel) AS FuelFee, sum(Advance) AS AdvanceFee, sum(Insurance) AS InsuranceFee, sum(Trailer) AS TrailerFee, 
    sum((Advance)+(Insurance)+(Trailer)+(Fuel)) AS TotalExp
    FROM TblExp
    GROUP BY CustName;
    

    当我尝试将它们组合时,结果是9(3 * 3),记录为我预期的只有3条记录。

    [TblLInfo,(表负载信息),用于收集每位客户运送的负载] [1]

    [TblExp(表费用),用于收集每位客户的每周费用] [2]

    [查询TblLInfo,获取特定客户的所有负载总和并减去发货费用,这样我们就可以获得净工资] [3]

    [查询TblExp,获取特定客户的总费用] [4]

    ![在此处输入图片说明] [1]

    ![在此输入图片说明] [2]

1 个答案:

答案 0 :(得分:0)

SELECT a.CustName,a.NetPay,b.TotalExp,(b.TotalExp-a.NetPay) AS overall_profit 
FROM
(SELECT CustName, sum(Rate) AS RateFee, sum(Disp_Fee) AS DispFee, sum(Rate*0.05) AS QuickPay, sum((Rate)-((Rate*0.05)+(Disp_Fee))) AS NetPay FROM TblLInfo GROUP BY CustName) a 
INNER JOIN 
(SELECT CustName, sum(Fuel) AS FuelFee, sum(Advance) AS AdvanceFee, sum(Insurance) AS InsuranceFee, sum(Trailer) AS TrailerFee, sum((Advance)+(Insurance)+(Trailer)+(Fuel)) AS TotalExp FROM TblExp GROUP BY CustName)b