从另一个表插入特定列

时间:2015-01-29 18:54:55

标签: sql insert sas

我正在尝试将一些值从一个表插入到另一个表中,并想知道如何使其成为可能。

表A有4列,其中A_1和A_2在某些行中为空白

表B中有3列,其中B_1和B_2为已填充

我想将B_1和B_2中的值分别插入到A_1和A_2中 行丢失了。 我确实在两者中都有相同的 id 用于加入目的。

我正在考虑下面的

proc sql;
    insert into A
    (A_1 , A_2)
    as select B_1 , B_2
    from B
    where A_1 = '' and A_2 = ''
;
quit;

2 个答案:

答案 0 :(得分:2)

我不熟悉SAS,你没有列出你的RBDM,但查询的基本思想是:

update tableA
set a_1 = b.b_1 ,
    a_2 = b.b_2
from tableA a
inner join tableB b on a.Id = b.Id
where a.a_1 is null
   and a.a_2 is null

你有一个insert语句的开头,但除非我误解你的场景,否则如果两个表之间存在ID,你实际上是在寻找更新。

请注意,这会将表a和b连接到" id"字段,然后使用b.b_1更新a.a_1,使用b.b_2更新a.a_2,仅在a.a_1和a.a_2都为null的情况下 - 我不确定您是否意味着null或空字符串。如果您的意思是空字符串,请使用a.a_1 is null

切换a.a_1 = ''

答案 1 :(得分:-1)

   data a;
   key = 1;
   a_1 = 4;
   a_2 = 6;
   output;
   key = 2;
   a_1 = .;
   a_2 = 6;
   output;
   key = 3;
   a_1 = 4;
   a_2 = .;
   output;
   run;

  data b;
  key = 1;
  b_1 = 14;
  b_2 = 62;
  output;
  key = 2;
  b_1 = 3;
  b_2 = 64;
  output;
  key = 3;
  b_1 = 54;
  b_2 =6 ;
  output;
  run;


    proc sql;
    create table a as
    select 
    coalesce(a_1,b_1) as a1,
    coalesce(a_2,b_2) as a2
    from a 
    left join b
    on
    (
    a.key = b.key
    );quit;

我使用左连接,因为我不想从a中删除行,以防它们从b中丢失。

这个程序会给你一个警告:

    WARNING: This CREATE TABLE statement recursively 
    references the  target table. A consequence of
    this is a possible data integrity problem.

但根据我的经验,它运作得很好。

相关问题