【问题标题】:Merge vs Proc sql合并与 Proc sql
【发布时间】:2017-08-17 19:28:31
【问题描述】:

我有两种方法可以做同样的事情,但没有得到相同的结果。这是什么原因?

第一种方式:

Proc sql;
    Create table abc.immu as
    select ID, DATE, CODE
    from xyz.imm
    where DATE between to_date('2008-01-01','YYYY-MM-DD') and to_date('2016-01-31','YYYY-MM-DD')
    Order by CODE);
        Quit;

Proc sql ;
    Create table abc.testb as
             select CODE, description from xyz.REF_code where lower(description)like '%hep b%';
 Quit;

proc sort data=abc.testb;
by code;
run;


data abc.testb1;
merge abc.immu(in=a) abc.testb (in=b);
by code;
if a=1 and b=1;
run;

第二种方式

Create table abc.testb1 as
        Select ID, DATE,CODE
    From xyz.imm
    where CODE in (select CODE from xyz.REF_code where lower(description)like '%hep b%')
    AND  DATE between to_date('2008-01-01','YYYY-MM-DD') and to_date('2016-01-31','YYYY-MM-DD')
    Order by ID, DATE;
    Quit;

proc sort data=abc.testb1 nodupkey;
by ID DATE;
run;

为什么没有得到相同的结果?这不是两种不同的方式来实现同一件事吗?

【问题讨论】:

  • 我的意思是观察结果相同
  • to_date() 在 SAS 中为您工作?这不是 SAS 代码 afaik,除非您使用直通,根据您发布的内容,这似乎没有发生。我认为如果您在任一表中有重复项,结果可能会有所不同。运行 PROC COMPARE 以查看结果的不同之处,这将帮助您隔离问题。
  • 是的,使用 pass through,即使没有运行 dup 键,观察结果也不相同
  • 第一种方法中没有NODUPKEY的等价物。

标签: merge sas proc-sql


【解决方案1】:

最好的猜测是您在第一个块的abc.testb 中有重复的CODE 记录。 abc.immu 表具有该代码,但对于 1 个或多个 CODE 值,记录比 testb 少。

举个例子:

测试数据:

data test;
do cd='a','b','c';
    do i=1 to 10;
        output;
    end;
end;
run;

data cds;
do cd='a','c';
    desc=1;
    output;
    desc=2;
    output;
end;
run;

当test 中的每个代码都有更多记录时,两者都可以正常工作。下面生成相同的记录。

proc sql noprint;
create table sql as
select * from test
    where cd in (select cd from cds);
quit;

data dataStep;
merge test(in=a) cds(in=b);
by cd;
if a and b;
run;

但是,如果我们在 test 中将 cd="a" 组剥离为仅 1,则会出现问题:

data test2;
set test;
if cd='a' then
    if i=1;
run;

proc sql noprint;
create table sql2 as
select * from test2
    where cd in (select cd from cds);
quit;

data dataStep2;
merge test2(in=a) cds(in=b);
by cd;
if a and b;
run;

现在dataStep2多了一条记录。

要解决此问题,您有几个选择:

  1. 从选择中删除description 列并使用DISTINCT 关键字。那么testb 每个CODE 将只有 1 行。
  2. 使用 SQL 解决方案。

【讨论】:

  • 我检查了代码,测试b每个代码只有1行
  • 没有数据和工作示例,我们必须猜测。正如我所说,这是一个猜测。如果您可以通过示例复制问题,那么有人可以解释该问题。见stackoverflow.com/help/mcve
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多