暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 根据特定条件从表B插入表A

ASKTOM 2020-07-20
160

问题描述

嗨,汤姆,

我有一个问题,即如何根据特定条件将数据从表B插入到表a。

例如,假设表A有EmpId、DepId、SalFreq、TotPaychecks和
表B有EmpId、DepId、Freq、Pay

create table A (
  EmpId number(18,0),
  DepId number(10,0),
 SalFreq varchar2(32),
  TotPaychecks number(3,0)
);

create table B (
  EmpId number,
  DepId number,
 Freq varchar2(2),
 Pay number(3)
);

insert into A values(1, 1, 'Monthly',12);
insert into A values(2, '1', 'Biweekly',26);
insert into A values(3, '2', 'Fortnightly',24);

insert into B values(4, '2',null,null);
insert into B values(5, '3', null,null);
insert into B values(6, '3', F,12);

复制




如果一个.EmpId!= B. EmpId和B.DepId!= null,
然后在a,B.EmpId,B.DepId中插入一行,如果B.Freq = null,则A.SalFreq = 每月,如果B.Pay = null,则A.TotPaychecks = 12
否则在a,B.EmpId,B.DepId A.SalFreq = B.Freq,A.TotPaychecks = B.Pay中插入一行

After snapshot of the table.
select * from A;

     EmpId  DepId        SalFreq    TotPayChecks
----------  ----------  ---------   --------------
         1          1                 Monthly        12
         2         1                 Biweekly        26
         3         2                Fortnightly    24
         4         2                Monthly         12
         5         3                Monthly          12
         6         3                Fortnightly     24
复制


谢谢,
雅利安

专家解答

我不清楚逻辑如何与期望的输出相关。在任何情况下,原理都是相同的:

-从B中选择a中不存在匹配行的行
-使用大小写表达式根据需要操纵freq/pay值。

例如:

select empid, depid,
       case
         when b.freq is null then 'Monthly'
         else b.freq
       end freq,
       case
         when b.pay is null then 12
         else b.pay
       end pay
from   b
where  not exists (
  select * from a 
  where  b.empid = a.empid
);

EMPID    DEPID    FREQ       PAY   
       6        3 F              12 
       4        2 Monthly        12 
       5        3 Monthly        12 
复制


插入此结果 (Insert .. select),根据需要调整大小写表达式。
文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论