How would you approach a tricky SQL problem to correctly transform and validate the results?
Use the provided transaction, adjustment, account, and expected-result tables. Produce one row for each latest settled transaction, calculate its adjusted amount, and identify whether the result is valid, mismatched, incomplete, or associated with an unknown account.
Output
- Return
transaction_id, account_name, net_amount, expected_amount, variance, and validation_status.
- Include only the latest settled record for each transaction and exclude canceled transactions.
- Sort by
transaction_id ascending.
Output details
- Choose the latest record by highest
version_number, then latest loaded_at, then highest event_id, before requiring status settled.
- Treat missing adjustments as zero, and preserve a NULL
gross_amount as NULL net_amount.
- Set
variance to NULL when either net_amount or expected_amount is NULL; otherwise calculate net_amount - expected_amount without rounding.
- Use statuses
INVALID_SOURCE_AMOUNT, MISSING_EXPECTED_RESULT, UNKNOWN_ACCOUNT, VALID, and MISMATCH in that precedence order: source amount, expected result, account, equality, otherwise mismatch.