我们直接使用熟悉的SASHELP.CLASS作为测试数据集。
1
2
3
4
5
6
7
8
9
10
11
|
data class1;
set sashelp.class;
if _n_<=5;
run;
proc print;run;
data class2;
set sashelp.class;
if _n_<=3 or _n_ in (6 7 8);
run;
proc print;run;
|
如下图所示,红色部分为CLASS1和CLASS2两个数据集之间相同的观测,蓝色部分为两者之间不同的观测。

在DATA STEP中,如果想要得到CLASS2相比CLASS1有更新的观测,可以通过:
1
2
3
4
5
6
7
8
9
|
proc sort data=class1;by _all_;run;
proc sort data=class2;by _all_;run;
data update_row;
merge class1(in=a) class2(in=b);
by _all_;
if b and ^a;
run;
proc print;run;
|
如果想要得到两个数据集之间共同的观测,也很简单:
1
2
3
4
5
6
|
data common_row;
merge class1(in=a) class2(in=b);
by _all_;
if a and b;
run;
proc print;run;
|
那么在PROC SQL中该如何实现上述的功能呢?常规方法的比如inner join,left join就可以实现, 而这里的方法是需要介绍两个operator,EXCEPT与INTERSECT。
1
2
3
4
5
6
7
8
9
|
proc sql;
select * from class2
except select * from class1;
quit;
proc sql;
select * from class2
intersect select * from class1;
quit;
|
使用HASH对象来找出来两者之间的异同。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
data update_row2;
if _n_=1 then do;
declare hash h(dataset:"class1", ordered:"yes");
h.defineKey(all:"yes");
h.defineData(all:"yes");
h.defineDone();
end;
set class2;
if h.find() ne 0;
run;
data common_row2;
if _n_=1 then do;
declare hash h(dataset:"class1", ordered:"yes");
h.defineKey(all:"yes");
h.defineData(all:"yes");
h.defineDone();
end;
set class2;
if h.find() = 0;
run;
|
文章作者
阿Q
上次更新
2023-06-07
许可协议
原创文章,如需转载请注明文章作者和出处。谢谢!