Oracle update+with的使用情境,oracleupdate

來源:互聯網
上載者:User

Oracle update+with的使用情境,oracleupdate
drop table test purge;
create table test(
      id number,
      code varchar(20),
      name varchar(20)
    );
insert into test values(1,'201401','aaa');
insert into test values(2,'201402','bbb');
insert into test values(3,'201402','ccc');
insert into test values(4,'201403','ddd');
insert into test values(5,'201403','eee');
insert into test values(6,'201403','fff');
commit;

--現在有這個一個需求,如果code有重複,根據code進行分組加上1,2,3,
--如code=201402的記錄,code為:201402_1、201402_2
--1.可以用分析函數拼出code

SQL> select t.id,code||'_'||row_number() over(partition by code order by id) cc from test t;
        ID CC
---------- -------------------------------------------------------------
         1 201401_1
         2 201402_1
         3 201402_2
         4 201403_1
         5 201403_2
         6 201403_3
已選擇6行。
--2.用傳統寫法看行不行,發現不行
SQL> update test t set t.code=(select code||'_'||row_number()
         over(partition by code order by id) code
        from test t1 where t1.id=t.id);
已更新6行。
SQL> select * from test;
        ID CODE                 NAME
---------- -------------------- --------------------
         1 201401_1             aaa
         2 201402_1             bbb
         3 201402_1             ccc
         4 201403_1             ddd
         5 201403_1             eee
         6 201403_1             fff
已選擇6行。
SQL> rollback;

--看來需要建一個暫存資料表,然後用update和merge,不過還有一種寫法


--3.update和with組合
SQL> update test b set b.code=(
    with t as
    (select t.id,code||'_'||row_number() over(partition by code order by id) code
        from test t)
    select a.code from t a where a.ID=b.ID
    );
已更新6行。

SQL> select * from test;
        ID CODE                 NAME
---------- -------------------- --------------------
         1 201401_1             aaa
         2 201402_1             bbb
         3 201402_2             ccc
         4 201403_1             ddd
         5 201403_2             eee
         6 201403_3             fff


已選擇6行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.