简体   繁体   中英

How to transfer a field with different values to another table (like a left join with condition)

I show you what I want to do. I have to tables: have1 and have2 and I want to have the table "want". If date of have2 is between start_date and end_date I want to copy this field.

data have1;
informat Start_Date End_Date ddmmyy10.;
format Start_Date End_Date ddmmyy10.;
input id  Start_Date  End_Date;
datalines;
10 08/02/2020 07/03/2020
10 02/10/2020 18/10/2020
;;;;
run;
data have2;
infile datalines delimiter=',';
informat Date ddmmyy10.;
format Date  ddmmyy10.;
input id  Date  ;
datalines;
10,01/01/20
10,01/04/20
10,05/05/20
10,05/10/20
;;;;
run;
data want;
infile datalines delimiter=',';
informat Date Start_Date End_Date ddmmyy10.;
format Date Start_Date End_Date ddmmyy10.;
input id  Date  Start_Date  End_Date;
datalines;
10,01/01/20,.,.
10,15/02/20,08/02/2020,07/03/2020
10,01/04/20,.,.
10,05/05/20,.,.
10,05/10/20,02/10/2020,18/10/2020
;;;;
run;

The date 15/02/20, which is in your "want" dataset, is missing from your "have2" dataset. It is not in your have1 dataset either.

You first need to include it in one of your original datasets, so it can appear in your final dataset. It makes more sense to inlcude it in your have2 dataset, which is composed of individual date points:

data have2;
infile datalines delimiter=',';
informat Date ddmmyy10.;
format Date  ddmmyy10.;
input id  Date  ;
datalines;
10,01/01/20
10,01/04/20
10,15/02/20
10,05/05/20
10,05/10/20
;;;;
run;

After you include the missing date in your original dataset, the code I posted here before will get what you want:

proc sql;
create table want as
select distinct
t1.date,
case when t1.Date>t2.Start_Date and t1.date<t2.End_Date 
     then t2.Start_Date else . end as Start_Date format=DDMMYY10.,
case when t1.Date>t2.Start_Date and t1.date<t2.End_Date 
     then t2.End_Date else . end as End_Date format=DDMMYY10.,
t1.id  
from have2 t1
left join have1 t2 on t1.id=t2.id
group by id, date
having end_date=max(end_date);
quit;

Best,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM