我有一个贷款历史表,其中包含客户借入和偿还的所有贷款。有两种状态(在同一行)表示贷款借款和贷款偿还:LD =贷款支付而LP =贷款支付。
我的问题是这个,我试图找到:
表格结构
到目前为止,这是我的解决方案:
LP的
$amtdues = "select h.ac_no, loan_amt, MAX(trx_date) AS Last_Pay, MAX(principal+interest) as Last_Paid, disb_date, exp_date, principal+interest as loan_interest, MAX(principal-interest) as outstanding_balance, trx_date as payment_date from loanhist h, loans l where h.ac_no = '$id' and l.ac_no = '$id' and trx_type = 'LP' group by trx_date, loan_amt, disb_date, exp_date, h.ac_no, interest, principal, trx_date ";
$amts = sqlsrv_query($conn, $amtdues);
$lp = sqlsrv_fetch_array($amts, SQLSRV_FETCH_ASSOC);
对于LD
$amtdues2 = "select h.ac_no, loan_amt, MAX(trx_date) AS Last_Pay, disb_date, exp_date, principal+interest as loan_interest, MAX(interest+principal) as outstanding_balance, MAX(interest+principal) as installment, trx_date as payment_date from loanhist h, loans l where h.ac_no = '$id' and l.ac_no = '$id' and trx_type = 'LD' group by trx_date, loan_amt, disb_date, exp_date, h.ac_no, interest, principal, trx_date ";
$amts2 = sqlsrv_query($conn, $amtdues2);
$ld = sqlsrv_fetch_array($amts2, SQLSRV_FETCH_ASSOC);
我在html中的输出
<td><?php echo parseCurrency(abs($lmts['loan_limit']));?></td>
<td><?php echo parseCurrency(abs($ld['loan_interest']));?></td>
<td><?php echo parseCurrency(abs($ld['outstanding_balance'] - $lp['outstanding_balance']));?> </td>
<td><?php echo parseCurrency(abs($ld['installment']));?></td>
在我尝试这些查询后,我的值不正确。有人可以帮助姐姐出去吗?
答案 0 :(得分:1)
根据loanhist
的表格信息,并对loans
中的内容做出一些假设(并且loans
与loanhist
之间存在1:多关系),我认为这个查询会让你朝着正确的方向前进。
SELECT l.ac_no,
l.loan_amt,
l.disb_date,
l.exp_date,
SUM(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) -
SUM(CASE WHEN trx_type='LP' THEN h.principal+h.interest ELSE 0 END) AS outstanding_balance,
MAX(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) AS instalment_amount,
SUM(CASE WHEN trx_type='LD' THEN h.principal+h.interest ELSE 0 END) AS loan_amount,
MAX(CASE WHEN trx_type='LP' THEN trx_date ELSE NULL END) AS last_payment_date,
SUM(CASE WHEN trx_type='LP' THEN h.principal+h.interest ELSE 0 END) AS amount_paid
FROM loans l
JOIN loanhist h
ON h.ac_no = l.ac_no
WHERE l.ac_no = '$id'
GROUP BY l.ac_no, l.loan_amt, l.disb_date, l.exp_date