【问题标题】:Insert into Specific Column from other table从其他表插入特定列
【发布时间】:2015-01-29 18:54:55
【问题描述】:

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

表 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;

【问题讨论】:

    标签: sql insert sas


    【解决方案1】:

    我不熟悉 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
    

    您有一个插入语句的开头,但除非我误解了您的情况,否则如果两个表之间存在 ID,您实际上是在寻找更新。

    请注意,这会在“id”字段上连接表 a 和 b,然后用 b.b_1 更新 a.a_1,用 b.b_2 更新 a.a_2,仅在 a.a_1 和 a.a_2 都存在的情况下null - 我不确定你的意思是空字符串还是空字符串。如果您的意思是空字符串,请将@​​987654323@ 换成a.a_1 = ''

    【讨论】:

      【解决方案2】:
         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.
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-03
        • 2021-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-22
        • 2017-09-13
        • 1970-01-01
        相关资源
        最近更新 更多