使用oracle中的子查询更新/合并表

时间:2017-09-03 19:30:03

标签: oracle oracle11g oracle10g

我有一张下表 - AccountDetails

 Account_No   Request_Id   Issue_date    Amount   Details
   1              567       20150607      $156     Loan
   2              789       20170406      $765     Personal
   3                        20170216      $897     
   3              987       20160525      $345     Loan
   3              456       20170112      $556     Loan
   4              234       20171118      $987     Loan

我必须更新request_id,其中请求id为null,或者对于具有以下逻辑的帐户,Details为null。 需要根据发布日期获取帐户的最新请求ID,并且必须更新请求ID(最新请求ID + 1)WHERE request_id为null或details为null。所以结果应该是

 Account No   Request_Id   Issue_date    Amount   Details
   1              567       20150607      $156     Loan
   2              789       20170406      $765     Personal
   3              457       20170216      $897     
   3              987       20160525      $345     Loan
   3              456       20170112      $556     Loan
   4              234       20171118      $987     Loan

我尝试使用以下查询

MERGE INTO AccountDetails a
USING ( select Request_Id + 1,ROW_NUMBER() OVER (PARTITION BY B.Account_No 
ORDER BY B.Issue_date desc) AS RANK_NO 
          from AccountDetails ) b
ON ( a.Account_No = b.Account_No AND a.DETAILS IS  NULL)
WHEN MATCHED THEN 
UPDATE SET  a.Request_Id = b.Request_Id
WHERE B.RANK_NO = 1;

2 个答案:

答案 0 :(得分:1)

听起来你需要使用分析LAG函数来确定前一行的request_id,例如:

MERGE INTO account_details tgt
  USING (SELECT account_no,
                CASE WHEN request_id IS NULL THEN 1 + LAG(request_id) OVER (PARTITION BY account_no ORDER BY issue_date)
                     ELSE request_id
                END request_id,
                issue_date,
                amount,
                DETAILS,
                ROWID r_id
         FROM   accountdetails) src
    ON (tgt.rowid = src.r_id)
WHEN MATCHED THEN
  UPDATE SET tgt.request_id = src.request_id;

当然,这个设计看起来有点奇怪 - 为什么request_id null起初呢?它是一个独特的专栏吗?如果是这样,如果您最终使用替换ID复制现有的request_id会发生什么?此外,如果它是一个帐号的第一行,那么会发生什么?请求__

答案 1 :(得分:0)

update accountdetails set request_id=(select max(request_id)+1 from accountdetails) 
   where request_id is null and details is null;