sql多个表之间查询
通常的语句就是
proc sql;
select table1.var,table2.var from table1,table2
where table1.anyvar=table2.anyvar;
quit;
其运行机制是什么?
假设现在有如下需求:
data x;
input id;
cards;
1
2
2
2
5
5
3
3
;
run;
data y;
input id1 ticker;
cards;
1 2
1 3
1 3
2 14
2 14
5 4
5 4
3 1
3 2
6 6
;
run;
/*目的:生成一个数据集,包含两个变量,一个为id,一个为ticker,id为x中id唯一值,ticker为y中与x对应的id所对应的唯一的ticker*/
/*生成数据集z结果如下:*/
data z;
input id ticker;
cards;
1 2
1 3
2 14
5 4
3 1
3 2
;
run;
用一个sql步解决的话就是:
/*code:*/
proc sql;
select distinct x.id,y.ticker from x,y
where x.id=y.id1;
quit;
那么上述代码的原理到底是什么?如果没有distinct,我还能说出个一二来,现在distinct在多表之间利用
是怎么来的,想了半天,不知道以下的想法是否正确,望熟悉sql的同学指导一下:
/*以上sql的机制是不是如下:*/
/*step 1:*/
proc sql;
create table z1 as
select x.*,y.* from x,y;
quit; /*from语句起作用,full join*/
/*step 2:*/
proc sql;
create table z2 as
select * from z1
where id=id1;
quit; /*where语句起作用*/
/*step 3:*/
proc sql;
select distinct id,ticker from z2;
quit; /*select语句的作用*/
/*联合上述step 1,2,3就是:*/
proc sql;
select distinct x.id,y.ticker from x,y
where x.id=y.id1;
quit;
所有sql语句是不是都可以如下理解:
先对两个表full join, 然后根据where,或者on,选择full join之后的部分观测,然后再用select选择其中的部分变量?
望高手解惑
附利用data步代码:
proc sort data=x out=x1 nodupkey;
by id;
proc sort data=y out=y1(rename=(id1=id)) nodupkey;
by id1 ticker;
;
data z;
merge x1(in=_1) y1;
if _1;
by id;
run;