如何检索每张财务费用发票的未付金额?

How to retrieve unpaid amount of each invoice for finance charges?

我正在实施财务费用,但不知道如何检索每张发票的未付金额。我对 SQL 并不陌生,但是这个问题让我很困惑。如果我没有正确搜索,请原谅我。

那么,假设我有一张发票 table:

 id | amount   
----+--------------
 1  | 50.00         
 2  | 50.00      
 3  | 50.00     
 4  | 50.00    
 5  | 50.00

和付款 table:

amount   
--------------
50.00       
25.00   

结果集应该是这样的:

 invoice_id | unpaid_amount   
------------+--------------       
 2          | 25.00      
 3          | 50.00     
 4          | 50.00     
 5          | 50.00 

当然,要实现财务收费还有不少要加的,但我想我可以拿到剩下的。

编辑: 抱歉,我的疏忽。 id 不相关。删除了付款 ID 列。

编辑 2:这些是虚构的数字,现实生活中的数字可以是任何数字,因此无法在金额上进行匹配。

编辑 3: 在这里,我根据@GordonLinoff 第二个答案创建了一个 SQL Fiddle 来展示我目前所拥有的。我希望有一种比我编造的笨拙 SQL 更简洁的方法。

我想你想要一个 join:

select i.id as invoice_id,
       (i.amount - coalesce(p.amount, 0)) as net_amount
from invoice i left join
     payment p
     on i.id = p.id;

编辑:

或者,您可能需要:

select i.*,
       (case when sum(i.amount) over (order by i.id) < p.amount 
             then i.amount
             else greatest(p.amount - sum(i.amount) over (order by i.id) + i.amount, 0)
        end) as amount_paid
from invoice i cross join
     (select sum(amount) as amount
      from payment
     ) p;

Here 是一个 db<>fiddle.

您可以使用 LEFT JOIN 并从两个 table 中减去金额。 COALSECE是为了防止你在没有付款的情况下得到NULL

select
     i.id as invoice_id
    ,i.amount - coalesce(p.amount,0) as amount
from invoice i 
left join payments p
    on p.id = i.id

如果在您的 payments 表格中可以为一张发票支付多笔款项,您应该在将其加入 invoice 之前分组 payments

select
     i.id as invoice_id
    ,i.amount - coalesce(p.amount,0) as amount
from invoice i 
left join (select id, sum(amount) as amount  from payments group by id) p
    on p.id = i.id