sqlsasleft-joinproc-sql

Proc SQL Select Distinct SAS


I have a dataset, Have, that looks like this:-

ID    Group  Label_T
1763    A     Y
1763    A     M
6372    B     M

I want to join this dataset onto another dataset by distinct ID and have a conditional based on the variable Group like this:-

proc sql;
create table want as 
  select a.ID
  a.Qty
  (case when b.Group = 'A' then 'Right'
        when b.Group = 'B' then 'Left' end) as Category
 from work.test a
   left join (select distinct ID from work.have) b
        on a.ID=b.ID
;
quit;

I want the dataset to look like this:-

ID      Qty   Category
1763     28     Right
6372     30     Left
3908     41     <blank>

And for the IDs that weren't in the Have dataset to be left blank for the column Category. When I run this I keep getting the error: "Column Group could not be found in the table/view identified with the correlation name b." The column Group is not in the work.test dataset. I think I might have to have the conditional with ID instead of Group but I do I need an additional data set for the conditional then join?


Solution

  • If you have not Group column in work.test then you should use that column in subquery. It will work fine

    proc sql;
    create table want as 
      select a.ID
      a.Qty
      (case when b.Group = 'A' then 'Right'
            when b.Group = 'B' then 'Left' end) as Category
     from work.test a
       left join (select distinct ID, Group from work.have) b
            on a.ID=b.ID
    ;
    quit;