SQL · Financial analytics
Why a SQL Join Can Double Revenue
A two-line invoice shows how an ordinary join inflates revenue and how to check the result before it reaches a dashboard.
An invoice for $120 shows up as $240 in the sales dashboard. Both tables agree on the invoice number. The customer is right. The query runs. Where did the extra $120 come from?
Follow one invoice through the join
Take a fictional invoice, A17. Its header stores the total of $120. Its two detail lines are $80 for installation and $40 for materials. Join the header to the details on invoice number and you get two perfectly sensible rows. The first pairs $120 with $80. The second pairs $120 with $40. Now sum the header column. You just counted the same bill twice.
That error can hide through testing. A customer with only single-line invoices balances every time. A customer who buys a bundle breaks the report. A change in the mix of orders can even make revenue growth appear to accelerate.
Choose what one row represents
For revenue by customer, sum the invoice headers directly if they already contain the amounts you need. For revenue by product, use the amounts on the detail lines. If you need both the invoice total and its number of lines, reduce the details to one row per invoice before joining. In the query below, invoice_headers is the table with one row per invoice. The WITH clause names the grouped line items detail so the final query can join them by invoice ID. This example assumes invoice IDs are unique across the source.
WITH detail AS (
SELECT invoice_id, COUNT(*) AS line_count,
SUM(line_amount) AS line_total
FROM invoice_lines
GROUP BY invoice_id
)
SELECT invoice_headers.invoice_id, invoice_headers.invoice_total,
detail.line_count, detail.line_total
FROM invoice_headers
LEFT JOIN detail ON detail.invoice_id = invoice_headers.invoice_id
A17 now produces one row with a header total of $120, two lines, and a line total of $120. The left join also keeps a header whose details are missing. A blank detail total is worth investigating before someone turns it into a zero.
Test the tempting shortcut
Add a second $120 invoice, B18, with one line. The correct total for the two invoices is $240. Summing the joined headers gives $360. Using SUM(DISTINCT invoice_total) gives $120 because it collapses two legitimate bills with the same price. Those three lines make a small, repeatable test for a reporting query.
Before shipping, reconcile the header count, the number of distinct invoice keys, and the total dollars to the source for the same period and currency. Check tax, shipping, and discounts separately if the line amounts exclude them. Then ask the analyst who owns the chart a simple question about any point on it. Can they trace the number back to the individual bills that earned it?