BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
mjkinchen
Calcite | Level 5


I have a set with multiple vars and two ID's: the first ID identifies the account owner, and the second ID identifies the user and records. EX:

a     1

a     1

a     1

a     2

a     2

a     3

a     3

b     1

b     1

b     2

.

z     5

I wish to collect all records with all account owners (a -....-z) and their FIRST user and records. EX:

a     1

a     1

a     1

b     1

b     1

etc.

Any thoughts on an efficient piece of code to do this?

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
SteveNZ
Obsidian | Level 7

A non-sql version:

proc sort data = have ;

    by id1 id2 ;

run ;

data want ;

set have ;

    by id1 id2 ;

        if first.id1 ;

run ;

View solution in original post

5 REPLIES 5
Linlin
Lapis Lazuli | Level 10

how about:

data have;
input id1 $ id2;
cards;
a     1
a     1
a     1
a     2
a     2
a     3
a     3
b     1
b     1
b     2
;

proc sql;
  create table want as
    select * from have
      group by id1
        having id2=min(id2);
quit;
proc print;run;

Linlin

mjkinchen
Calcite | Level 5

This worked REALLY well... Thanks! Smiley Happy

Alpay
Fluorite | Level 6

Expanding on Steve's code.

data want ;

    set have ;

    by id1 id2 ;

    retain _id1 _id2;

    if first.id1 then do;

      _id1 = id1;

      _id2 = id2;

    end;

    if _id1 = id1 and _id2 = id2;

    drop _id:;

run ;

Patrick
Opal | Level 21

If you really want the first user and not the user with the lowest id then Linlin's SQL won't give you the correct result. Some code like below would do:

data have;
  input ida $ idb $;
  datalines;
b 1
b 1
b 2
a 2
a 2
a 1
a 1
a 1
a 3
a 3
;
run;

data want(drop=_:);
  set have;
  by ida notsorted;
  retain _r_idb;
  if first.ida then _r_idb=idb;
  if idb=_r_idb then output;
run;

SteveNZ
Obsidian | Level 7

A non-sql version:

proc sort data = have ;

    by id1 id2 ;

run ;

data want ;

set have ;

    by id1 id2 ;

        if first.id1 ;

run ;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 1902 views
  • 7 likes
  • 5 in conversation