假设有 5 张发票属于同一客户。
发票ID | 金额 |
---|---|
1 | 200 |
2 | 400 |
3 | 300 |
4 | 500 |
客户支付1000
付款应全部应用于发票 1、2、3 和部分(100 应用于发票 4)
发票ID | 金额 | 付款 | 未付款 |
---|---|---|---|
1 | 200 | 200 | 0 |
2 | 400 | 400 | 0 |
3 | 300 | 300 | 0 |
4 | 500 | 100 | 400 |
尝试循环记录但失败。
kbr = me.payment
Do Until rs.EOF
If DLookup("closed", "invoice", "bilid=" & rs!Utility) = 0 And rs!Charges > 0 Then
If kBr >= rs!Charges Then
DoCmd.RunSQL "insert into advdep ( advbill, advdate, adv_amt, advmode, payref ) values ( " & rs!Utility & " , #" & AdvDate & "#, " & rs!Charges & " , Advmode, payref) " ': DoCmd.RunSQL "update invoice set paidamt=paidamt + " & rs!Charges & ", closed = 1 where bilid=" & rs!Utility & " and closed = 0"
ElseIf kBr > 0 Then
DoCmd.RunSQL "insert into advdep ( advbill, advdate, adv_amt, advmode, payref ) values ( " & rs!Utility & " , #" & AdvDate & "#, " & (rs!Charges - kBr) & " , Advmode, payref) " ': DoCmd.RunSQL "update invoice set paidamt=paidamt + " & rs!Charges & ", closed = 1 where bilid=" & rs!Utility & " and closed = 0"
Else
Exit Do
End If
kBr = kBr - rs!Charges
rs.MoveNext
Loop
考虑纯 SQL 并通过使用运行总和窗口函数来计算总付款来避免使用 VBA。 MariaDB 支持窗口函数,Access 可以通过引用原始数据库表而不是链接表的直通查询运行更新查询。
请参阅 dbfiddle 演示解决方案,并对数据库结构(即客户、发票和付款表)进行假设。
UPDATE invoices i
INNER JOIN (
SELECT
i.customer_id,
i.invoice_id,
i.amount AS invoice_amount,
SUM(i.amount) OVER(
PARTITION BY i.customer_id
ORDER BY i.invoice_id
) AS invoice_running_sum,
p.amount AS payment
FROM invoices i
INNER JOIN payments p
ON i.customer_id = p.customer_id
) sub
ON i.invoice_id = sub.invoice_id
SET i.paid = (
CASE
WHEN sub.invoice_running_sum < sub.payment
THEN 0
ELSE sub.invoice_running_sum - sub.payment
END
);