我一直在寫SQL查詢多年,但我堅持在這一個。計算貸款支付時支付滿意 - 部分支付允許
我有2代表在MySQL:
- LOANPAYMENTSDUE包括
LoanPaymentsDueId
,LoanId
,AmtDue
,DueDate
- LOANPAYMENTS包括
LoanPaymentsId
,LoanId
,AmtPaid
,PaidDate
的之間關系表是LoanId
,而不是到期的具體付款。在完美的世界DueDate = PaidDate
和AmtDue = AmtPaid
。然而,對我而言,這個複雜的是LoanPaymentsDueId
和LoanPaymentsId
之間沒有關係。該關係僅在LoanId
存在,允許在單一LOANPAYMENTSDUE付款上進行部分付款。
我研究了網絡,試圖找到正確的查詢創建一個報告,顯示每個LOANPAYMENTSDUE滿意的日期。這需要計算LOANPAYMENTSDUE.DueDate的餘額,因爲可能會錯過付款,並且新付款應該滿足最早的LOANPAYMENTSDUE付款的餘額。
這裏是樣本數據和表腳本:
CREATE TABLE LOANPAYMENTSDUE (
LoanPaymentsDueId BIGINT(20) NOT NULL AUTO_INCREMENT
, LoanId BIGINT(20)
, AmtDue double NOT NULL
, DueDate date NOT NULL
, PRIMARY KEY (LoanPaymentsDueId)
);
INSERT INTO LOANPAYMENTSDUE (LoanId, AmtDue, DueDate) VALUES (1, 100, '2013-07-15');
INSERT INTO LOANPAYMENTSDUE (LoanId, AmtDue, DueDate) VALUES (1, 100, '2013-08-15');
INSERT INTO LOANPAYMENTSDUE (LoanId, AmtDue, DueDate) VALUES (1, 100, '2013-09-15');
INSERT INTO LOANPAYMENTSDUE (LoanId, AmtDue, DueDate) VALUES (1, 100, '2013-10-15');
INSERT INTO LOANPAYMENTSDUE (LoanId, AmtDue, DueDate) VALUES (1, 100, '2013-11-15');
CREATE TABLE LOANPAYMENTS (
LoanPaymentsId BIGINT(20) NOT NULL AUTO_INCREMENT
, LoanId BIGINT(20)
, AmtPaid double NOT NULL
, PaidDate date NOT NULL
, PRIMARY KEY (LoanPaymentsId)
);
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 100, '2013-07-15'); /* Full pmt on due date */
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 100, '2013-08-10'); /* Full pmt a few days early */
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 100, '2013-09-22'); /* Full pmt a week late */
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 50, '2013-10-18'); /* Partial pmt a few days late */
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 50, '2013-11-07');/* Partial pmt 3 weeks late and satisfies the 10/15/2013 balance on this date */
INSERT INTO LOANPAYMENTS (LoanId, AmtPaid, PaidDate) VALUES (1, 100, '2013-11-22');/* Full pmt a week late and satisfies the 11/15/2013 pmt due */
報告查詢應該簡單地提供PAIDDATE當每個LOANPAYMENTSDUE很滿意。使用報告上面的表中的數據將是如下:
LOANID LOANPAYMENTSDUEID AMTDUE DUEDATE PAIDDATE
1 1 100 2013-07-15 2013-07-15
1 2 100 2013-08-15 2013-08-10
1 3 100 2013-09-15 2013-09-22
1 4 100 2013-10-15 2013-11-07
1 5 100 2013-11-15 2013-11-22
哇,這是一個具有挑戰性的真正感謝 –