有一个需求是查询下面表A中的code字段的值,----------------------------------------------------------------------------------------------------------------------------------------
tableA
----------------------------------------------------------------------------------------------------------------------------------------
code     |    fund1     |    unit1  | fund2     |    unit2  | fund3     |    unit3  | fund4      |   unit4
----------------------------------------------------------------------------------------------------------------------------------------
BANCA01  | BANCA01  | 7     |    BANCA02 | 6     |    BANCA03 | 8     |    BANCA04  | 5
-----------------------------------------------------------------------------------------------------------------------------------------若是code的值为'BANCA01'时将查询结果替换成后面fund也为'BANCA01'对应的unit的值,现在关键是四个fund字段中任意一个都有可能是'BANCA01',替换查询用decode还好办,但是后面这样不确定的查询,我处理不好逻辑,该怎么写才好呢,在这里恭请各位老师们帮忙指点一下迷津,学生不胜感激!

解决方案 »

  1.   

    update tableA t
       set code =
           (select unit1
              from tableA h
             where t.code = h.fund1
            union all
            select unit2
              from tableA h
             where t.code = h.fund2
            union all
            select unit3
              from tableA h
             where t.code = h.fund3
            union all
            select unit4
              from tableA h
             where t.code = h.fund4);
      

  2.   

    查询
    select code,(case when code=fund1 then unit1
    when code=fund2 then unit2
     when code=fund3 then unit3
       when code=fund3 then unit4
       end) new_code from tableA;
       
       
    不确定你的 code是否是有重复,所以用rowid写  
    修改
    merge into tableA a using (select rowid aaa ,code,(case when code=fund1 then unit1
    when code=fund2 then unit2
     when code=fund3 then unit3
       when code=fund3 then unit4
       end) new_code from tableA) b
       on (a.rowid=b.aaa) 
       when matched then 
         update set 
         a.code=b.new_code;