【发布时间】:2013-11-27 20:19:40
【问题描述】:
多年来我一直在编写 SQL 查询,但我一直坚持这个。
我在 MySQL 中有 2 个表:
- LOANPAYMENTSDUE 包括
LoanPaymentsDueId、LoanId、AmtDue、DueDate - 贷款支付包括
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 */
报告查询应在满足每个 LOANPAYMENTSDUE 时简单地提供 PAIDDATE。使用报告上方的表格数据如下:
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
【问题讨论】:
-
哇这个真的很有挑战性