【问题标题】:How can I use Proc SQL to find all the records that only exist in one table but not the other?如何使用 Proc SQL 查找仅存在于一个表中而不存在于另一个表中的所有记录?
【发布时间】:2012-01-20 19:09:33
【问题描述】:

我正在企业指南中尝试通过一项任务执行此操作,否则我只会使用数据步骤。

在数据步骤中,这将是:

data names;
 input name $;
 datalines;
  John
  Mary
  Sally
  Fred
  Paul
 ;
run;

data check;
 input name $;
 datalines;
  Mary
  Fred
 ;

Proc sort data=names; by name; run;
Proc sort data=check; by name; run;

Data work.not_in_check;
 merge names(in=n) check(in=c);
 by name;
 if n and not c;
run;

【问题讨论】:

    标签: sql sas


    【解决方案1】:

    这是一种方法。肯定还有很多其他的。

    proc sql;
     create table not_in_check as
     select name
     from names
     where name not in (select name from check);
    quit;
    

    【讨论】:

      【解决方案2】:

      另一个细微的变化是:

      proc sql;
      create table not_in_check as select 
       a.* from names as a left join 
                check as b on
                a.name=b.name
                where b.name is null;
      quit;
      

      【讨论】:

      • 这是我最终在 EG 中使用的方法。在过滤数据部分,我使用了 b.name is missing。很高兴看到解释为什么当我希望 a.name 不存在于 b 中时,b.name is null(missing) 会发生这种情况....
      • 这是因为正在读入 2 列,a.name 和 b.name。然后匹配它们,因此如果 a 中存在名称但 b 中不存在名称,则 b.name 记录将丢失。带有 is null where 子句的左连接确保您只将名称保留在 a 而不是 b。 select a.* 确保它只输出表 a 中的数据,即使它正在从两个表中读取数据。希望这会有所帮助。
      【解决方案3】:

      以下方法是获取一个表中存在的记录而不是另一个表中的记录的非常简单的方法。

      新建表,记录为sex = M,查询后的结果为sex = F的记录。

      例子:

      data new;
      set sashelp.class;
      where sex = 'M';
      run;
      proc sql;
      create table new1 as
      select * from sashelp.class
      except all 
      select * from new;
      quit;
      

      将代码在我大约 100k obs 的实际数据集上进行测试并更新结果。

      P.S:我知道这个问题已被回答并被遗忘,我正在寻找一种方法来完成上述操作,但在任何地方都找不到直接答案。因此,添加以便它可以派上用场。 :)

      我的第一个答案也是。 :)

      【讨论】:

        【解决方案4】:
        proc sql;
         create table inNamesNotIncheck
         as
         select *
         from names n
         where not exists
         (select name
         from check c
         where n.name=c.name);
        quit;
        

        【讨论】:

        • 您好,您的帖子已被标记为“低质量”,可能是因为它仅包含代码。您可以通过解释这究竟是如何以及为什么回答问题来大大改进您的答案?
        • 感谢添加代码。它显示了一种不同但可行的方法来解决已经描述的问题。谢谢。
        猜你喜欢
        • 2012-08-30
        • 2020-05-11
        • 1970-01-01
        • 1970-01-01
        • 2016-06-14
        • 2014-06-26
        • 1970-01-01
        • 2010-09-26
        • 2018-05-30
        相关资源
        最近更新 更多