zoukankan      html  css  js  c++  java
  • Oracle update+with的使用场景

    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行。

  • 相关阅读:
    华为云DevCloud为开发者提供高效智能的可信开发环境
    【HC资料合集】2019华为全联接大会主题资料一站式汇总,免费下载!
    在modelarts上部署mask-rcnn模型
    独立物理机和虚拟机比较有什么优势?
    .Net Core下使用MQTT协议直连IoT平台
    解惑Python模块学习,该如何着手操作...
    sar命令,linux中最为全面的性能分析工具之一
    窥探日志的秘密
    Debian 如何使用测试版更新软件包到最新的版本
    如何使用vsphere client 克隆虚拟机
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7112095.html
Copyright © 2011-2022 走看看