根据条件将正确的值作为一个变量拉出

时间:2018-11-15 17:55:07

标签: sql join sas outer-join case-when

基本上我要说的是: 如果键上有匹配项,则根据日期将正确的(新)值插入变量。如果没有匹配项,那么我想要旧表中的值,下面是我的示例代码:

    proc sql;
create table fly.Formulary2017
as select
d.corp_ent_cd
,d.groupno
,case when p.EffectiveDate > d.cvmo
        then d.old
when p.EffectiveDate <= d.cvmo
        then p.new
else d.old
        end as WANT
,d.Key1
from lib.dsl d FULL JOIN lib.post p
on d.Key1=p.Key1
;   
quit;

因此每个键不一定都匹配。对于那些没有匹配项的,我想要旧值。

1 个答案:

答案 0 :(得分:1)

您需要在代码中包括匹配记录逻辑,如下所示。这是下面的小示例代码。我已经分配了“新”和“旧”,您可以改为使用列。

 /***partial code.***/

case when d.Key1 = p.Key1  and p.EffectiveDate > d.cvmo
    then "new"
when d.Key1 ne p.Key1
 then "old"
  when d.Key1 = p.Key1 and  p.EffectiveDate <= d.cvmo
    then "old"


 /*full code to try*/

 data post;
input key1 EffectiveDate:date9. ;
 format EffectiveDate date9.;
datalines;
10 10OCT2018 
11 22OCT2018 
12 27OCT2018
15 10NOV2018
16 22NOV2018
 17 27NOV2018
;

data dsl;
input key1 cvmo:date9. ;
format cvmo date9.;
datalines;
10 17OCT2018 
11 1OCT2018 
16 22NOV2018 
17 27NOV2018 
;

proc sql;
select
p.key1,
, case when d.Key1 = p.Key1  and p.EffectiveDate > d.cvmo
    then "new"
when d.Key1 ne p.Key1
 then "old"
  when d.Key1 = p.Key1 and  p.EffectiveDate <= d.cvmo
    then "old"
    end as WANT

from dsl d FULL JOIN post p
on d.Key1=p.Key1
 ;   
quit;