¿Buscar valores en una tabla y agregarlos al conjunto de datos de acuerdo con la condición IF (MERGE / SQL)?

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;

Here's an example with a bit of the data...

LOOKUP table (3 vars):

LoadPort LoadCountry  LoadArea

MASTER (many vars):

OBS    LoadPort  LoadCountry LoadArea  LPortMiss
1                 ALGERIA    NAF        1

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

Can you give an example with some data? Also, you should go back to your other question and "accept" the answer that worked for you, as suggested in one of the comments there. This gives people an incentive to answer your question. -

2 Respuestas

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;

El coalesce function returns the first non-missing argument, so if loadport is missing from table master then it takes it from table lookup.

By the way, this isn't specific to SAS. For questions like this you could use a SQL etiqueta.

Respondido 01 Feb 12, 19:02

Thanks, that worked, though to preserve the whole data set I've modified it to be: proc sql; select coalesce(a.loadport,b.loadport), * from master a left join lookup b on a.loadcountry=b.loadcountry and a.loadarea=b.loadarea; quit; - Sasafrás

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;

Respondido 01 Feb 12, 21:02

Good alternative! Thanks so much to both of your responses. - Sasafrás

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.