I need to lookup data from one table and add it to a master data table based on an if condition: whether the data is flagged as missing. Say the lookup table contains countries and ports. There are missing port names in the master file that need to be filled. It fills these using the lookup only if flag = 1 (it's missing).
This command doesn't work (won't fill it in & won't keep the obs with Flag =0):
proc sql; create table data.varswprice1 as select * from data.varswprice a left join data.LPortsFill b on a.LoadCountry = b.LoadCountry and a.LoadArea = b.LoadArea where LPortMiss = 1; quit;
Here's an example with a bit of the data...
LOOKUP table (3 vars):
LoadPort LoadCountry LoadArea ARZEW ALGERIA NAF
MASTER (many vars):
OBS LoadPort LoadCountry LoadArea LPortMiss 1 ALGERIA NAF 1 2 ADELAIDE AUSTRALIA SEOZ 0
So, it needs to fill in the first obs in MASTER with the first obs in LOOKUP (ARZEW) based on the fact that LPortMiss = 1 and LoadCountry and LoadArea are equal. There are many more obs in LOOKUP and MASTER but I hope this illustrates the problem better.
preguntado el 01 de febrero de 12 a las 14:02
Creo que esto es lo que estás buscando:
proc sql; select coalesce(a.loadport,b.loadport), a.loadcountry, a.loadarea from master a left join lookup b on a.loadcountry=b.loadcountry and a.loadarea=b.loadarea; quit;
coalesce function returns the first non-missing argument, so if
loadport is missing from table
master then it takes it from table
By the way, this isn't specific to SAS. For questions like this you could use a
You can also use the UPDATE function in proc sql, this saves having to create a new dataset. You would probably want to reset the lportmiss flag as well.
proc sql; update master as a set loadport=(select loadport from lookup as b where a.LoadCountry=b.LoadCountry and a.LoadArea=b.LoadArea) where lportmiss=1; quit;