Run a SQL query which pulls up a list of invoices including its most recent transaction.
Requirements:
- get this information using 1 query (inner queries might be necessary)
- include invoices that do not have a transaction yet
- able to filter by fields on the invoice or transaction. example scenarios below:
- example 1: all invoices whose last transaction status is
settled
- example 2: all invoices whose status is
unpaid
which do not have a last transaction)
- example 1: all invoices whose last transaction status is
The tricky part is that we are dealing with a many-to-many scenario. All StackOverflow posts I found were regarding one-to-many scenarios. The following SO post seemed to take me in the right direction, but could not quiet figure it out: SQL join: selecting the last records in a one-to-many relationship
The reason I have a many-to-many here is because a transactions can be part of many invoices. Basically several invoices can be assigned to the same payment profile, therefore we create one transaction (instead of having a separate transactions for each invoice). In addition, an invoice can have many transactions since transactions can be declined.
I know you may think, why not have an overarching invoice and then have the current invoices be invoice_lines, or something along those lines, but unfortunately the schema cannot be changed at this time.
Here is an outline my tables:
Any help would be great appreciated!