如何使用proc比较来更新数据集

时间:2014-10-17 08:18:53

标签: compare sas

我想每天使用proc compare更新数据集。

work.HAVE1

Date        Key Var1 Var2 
01Aug2013   K1   a    2
01Aug2013   K2   a    3
02Aug2013   K1   b    4

work.HAVE2

Date        Key Var1 Var2 
01Aug2013   K1   a    3
01Aug2013   K2   a    3
02Aug2013   K1   b    4
03Aug2013   K2   c    1

DateKey唯一确定一条记录。 如何使用上面的两个表构建以下

work.WANT

Date        Key Var1 Var2 
01Aug2013   K1   a    3
01Aug2013   K2   a    3
02Aug2013   K1   b    4
03Aug2013   K2   c    1

我不想删除以前的数据,然后重建它。我希望modify通过在底部添加新记录并调整VAR1VAR2中的值。 我正在与proc compare挣扎,但它并没有回复我想要的东西。

2 个答案:

答案 0 :(得分:2)

proc compare base=work.HAVE1 compare=work.HAVE2 out=WORK.DIFF outnoequal outcomp;
id Date Key;
run;

这将在单个数据集WORK.DIFF中为您提供新的和更改的(不相等的记录)。你必须区分新的和改变自己。

但是,你想要实现的是MERGE - 插入新的,覆盖现有的,但可能由于性能原因等等,你不想重新创建完整的表。

data work.WANT;
    merge work.HAVE1 work.HAVE2;
    by Date Key;
run;

EDIT1:

/* outdiff option will produce records with _type_ = 'DIF' for matched keys */
proc compare base=work.HAVE1 compare=work.HAVE2 out=WORK.RESULT outnoequal outcomp outdiff;
id Date Key;
run;


data WORK.DIFF_KEYS;  /* keys of changed records */
    set WORK.RESULT;
    where _type_ = 'DIF';
    keep Date Key;
run;

/* split NEW and CHANGED */
data
    WORK.NEW
    WORK.CHANGED
;
 merge
      WORK.RESULT (where=( _type_ ne 'DIF'));
        WORK.DIFF_KEYS (in = d)
    ;
  by Date Key;
  if d then output WORK.CHANGED;
  else output WORK.NEW;
run;

EDIT2:

现在你只需要APPEND WORK.NEW到目标表。

对于WORK.CHANGED - 使用MODIFYUPDATE语句更新记录。 根据更改的大小,您还可以考虑PROC SQL; DELETE删除旧记录,PROC APPEND添加新值。

答案 1 :(得分:0)

所有PROC COMPARE都会告诉您2个数据集之间的差异。要实现您的目标,您需要在数据步骤中使用UPDATE语句。这样,HAVE1中的值将使用HAVE2更新,其中日期和键匹配,或者如果没有匹配则插入新记录。

data have1;
input Date :date9. Key $ Var1 $ Var2;
format date date9.;
datalines;
01Aug2013   K1   a    2
01Aug2013   K2   a    3
02Aug2013   K1   b    4
;
run;

data have2;
input Date :date9. Key $ Var1 $ Var2;
format date date9.;
datalines;
01Aug2013   K1   a    3
01Aug2013   K2   a    3
02Aug2013   K1   b    4
03Aug2013   K2   c    1
;
run;

data want;
update have1 have2;
by date key;
run;