In my case i have three tables. The Contracts table, the agreements table and the payments table. What i have is a table with contracts which represents the value in debt, another table with the agreements of the conditions to pay off the debt, and another table related to the agreements table who has the debt split in parcels.
ContractsTable
(Id | Number | Name | Debt | ...)
1 | 1234 | AAAAAA | 1250,00 € | ...
2 | 1235 | BBBBBB | 5000,20 € | ...
3 | 1236 | CCCCCC | 500,00 € | ...
AgreementsTable
(Id | ContractId | Debt | IsValid | ...)
1 | 1 | 1250,00 € | 1 | ...
2 | 2 | 5000,20 € | 0 | ...
3 | 2 | 5000,20 € | 1 | ...
4 | 3 | 500,00 € | 0 | ...
PaymentsTable
(Id | AgreementId | Date | Amount | IsPaid | ...)
1 | 1 | 01/08/2012 | 500,00 € | 1 | ...
2 | 1 | 01/09/2012 | 500,00 € | 1 | ... -> Last payment
3 | 1 | 01/10/2012 | 250,00 € | 0 | ... -> Next Payment
4 | 3 | 01/08/2012 | 1000,00 € | 1 | ...
5 | 3 | 01/09/2012 | 1000,00 € | 1 | ...
6 | 3 | 01/10/2012 | 1000,00 € | 0 | ...
7 | 3 | 01/11/2012 | 1000,00 € | 0 | ...
8 | 3 | 01/12/2012 | 1000,20 € | 0 | ...
So when i execute the stored procedure to get the table with the contracts, i want to somehow see a column with the date of last payment that was done and the date of next payment to be done too. But i will only be able to see the date of the last payment done and the date of the next payment to be done if the contract has a valid agreement related with and in the case of the next payment only if the agreement is valid.
I am working with MS Sql Server.
Thanks in advance!
Will this work for you?
I used ‘min’ for the Next Payment Date assuming there’s multiple next payment dates.
SQL Fiddle