oracle 我有一个表与贷款帐户,从该表中,我想得到当前正在进行的贷款和其各自的以前,但仍在进行的贷款帐户

4urapxun  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(137)

该表有像open_date,close_date,first_disb_date这样的信息,当我尝试比较prev_loan.date_last_disb < Curr_loan.date_acct_open时,我会得到我想要的结果,但如果客户在同一日期获得了两笔贷款,当我只需要当前贷款之前的最后一笔贷款时,我会得到两个账号

SELECT ds.cust_id,

        dt.acct_no curr_loan,

        ds.acct_no prev.loan

   FROM acct_dtls dt

  INNER JOIN acct_dtls ds

     ON (dt.cust_id = ds.cust_id)

  WHERE dt.date_last_disb IS NOT NULL

    AND ds.date_last_disb =

        (SELECT MAX(s.date_last_disb)

           FROM acct_dtls s

          WHERE s.cust_id = dt.cust_id

            AND s.date_last_disb < dt.date_last_disb)
bwleehnv

bwleehnv1#

Updated code to suit your requirements:

WITH RankedAccounts AS (
  SELECT
    ds.cust_id,
    dt.acct_no AS curr_loan,
    ds.acct_no AS prev_loan,
    ROW_NUMBER() OVER (PARTITION BY ds.cust_id ORDER BY ds.date_last_disb DESC) AS RowNum
  FROM acct_dtls dt
  INNER JOIN acct_dtls ds
    ON (dt.cust_id = ds.cust_id)
  WHERE dt.date_last_disb IS NOT NULL
    AND ds.date_last_disb < dt.date_last_disb
)

SELECT cust_id, curr_loan, prev_loan
FROM RankedAccounts
WHERE RowNum = 1;
ijxebb2r

ijxebb2r2#

对于每个客户,您需要一个包含最终和倒数第二个贷款的结果行。实现此目的的一种方法是使用LAG获取行的precedent,使用LEAD获取行的successor:

SELECT
  cust_id,
  acct_no as current_loan, 
  prev_acct_no as previous_loan
FROM
(
  SELECT
    cust_id,
    acct_no,
    LAG(acct_no) OVER (PARTITON BY cust_id ORDER BY date_last_disb) AS prev_acct_no,
    LEAD(acct_no) OVER (PARTITON BY cust_id ORDER BY date_last_disb) AS next_acct_no
  FROM acct_dtls
  WHERE date_last_disb IS NOT NULL
) with_prev_and_next
WHERE next_acct_no IS NULL
ORDER BY cust_id;

相关问题