您好,我想在表格发票中添加一个名为Profit的列。我想确切地获得红色的值。该值是使用表loadNumber作为ID减去表发票amountUsd列MINUS表carrierPayments amountUsd列的值。如果我使用以下查询在每张发票中有一个carrierPayments,则可以使用。
SELECT i.*, i.amountUsd - cp.amountUsd AS PROFIT FROM invoice i INNER JOIN carriersPayments cp ON i.loadNumber = cp.loadNumber
但是,如果我有不止一个带有与橙色背景相同的loadNumber的carrierPayment。可以将多个承运人付款减去一张发票吗?
答案 0 :(得分:0)
您可以使用join
和group by
:
select i.*,
(i.amountUSD - coalesce(p.amountUSD, 0)) as profit
from invoice i left join
(select p.loadNumber, sum(p.amountUSD) as amountUSD
from carrierPayments p
group by p.loadNumber
) p
on p.loadNumber = i.loadNumber;
答案 1 :(得分:0)
SELECT i.*, i.amountUsd - sum(cp.amountUsd) AS PROFIT FROM invoice i INNER JOIN carriersPayments cp ON i.loadNumber = cp.loadNumber group by cp.loadNumber