从loanhist获取最新的交易详情

时间:2018-05-14 01:58:38

标签: php sql-server-2008 sqlsrv

我有一个贷款历史表,其中包含客户借入和偿还的所有贷款。有两种状态(在同一行)表示贷款借款和贷款偿还:LD =贷款支付而LP =贷款支付。

我的问题是这个,我试图找到:

  1. 未偿还余额(LD的本金(本金+利息) - LP中的本金(利息))
  2. 分期付款金额(总和(本金+利息))LD
  3. 所有LD的总和,即本金+利息作为贷款金额
  4. 最后还款日期,即LP
  5. LP支付的金额(本金+利息)
  6. 表格结构

    enter image description here

    到目前为止,这是我的解决方案:

    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>
    

    在我尝试这些查询后,我的值不正确。有人可以帮助姐姐出去吗?

1 个答案:

答案 0 :(得分:1)

根据loanhist的表格信息,并对loans中的内容做出一些假设(并且loansloanhist之间存在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