DEV Community

Nadiia Antonenko for Stimul Training Center

Posted on Fully Autonomous

Why two partial payments can double an invoice total in SQL

A supplier invoice has two lines, one for 80 and one for 40. Accounts payable has recorded two payments against it, first 30 and then 20. The supplier is still owed 70. Suppose your ERP report shows an outstanding balance of 140. Before you inspect the payment postings, count the rows going into your sums.

Here is the entire example. Each amount is in the same currency, and each payment row records the amount applied to this invoice.

Table Invoice ID Row ID Amount
invoice_lines 101 L1 80
invoice_lines 101 L2 40
payments 101 P1 30
payments 101 P2 20

Joining the two tables on invoice ID gives each line a match with both payments. Line L1 appears beside P1 and P2, and so does L2. Summing these four rows counts 80 and 40 twice, giving 240 invoiced. It also counts 30 and 20 twice, giving 100 paid. Subtracting one inflated total from the other gives the mysterious 140.

The report needs one row per invoice. First group each table by invoice ID so that each side of the join already has one row per invoice. A left join then keeps invoices that have lines but no payments.

WITH billed AS (
    SELECT invoice_id, SUM(amount) AS invoice_total
    FROM invoice_lines
    GROUP BY invoice_id
),
paid AS (
    SELECT invoice_id, SUM(amount) AS paid_total
    FROM payments
    GROUP BY invoice_id
)
SELECT b.invoice_id, b.invoice_total,
       COALESCE(p.paid_total, 0) AS paid_total,
       b.invoice_total - COALESCE(p.paid_total, 0) AS balance
FROM billed b
LEFT JOIN paid p ON p.invoice_id = b.invoice_id;
Enter fullscreen mode Exit fullscreen mode

For invoice 101 the result is 120 invoiced, 50 paid, and 70 outstanding. As a second check, remove both payment rows. The result should be 120 invoiced, zero paid, and 120 outstanding. COALESCE supplies that zero when the join finds no payment.

One tempting shortcut is SUM(DISTINCT amount). Imagine the supplier receives two payments of 25 each. Both belong in the paid total. Removing duplicate amounts would quietly discard one of those payments.

If you're checking the report with an accountant, agree on which postings settle the supplier balance before mapping them to payment rows. Stimul Training Center covers the accounting side in its Ukrainian material on supplier settlements.

Top comments (0)