BookmarkSubscribeRSS Feed
ahtinuS
Fluorite | Level 6

Good day,

I require help with the following:

1. For the 1st instance of A, if B > 0 then set C to 1 else set to 0.

2. For the next (2nd) instance of A, if B > 0 increase C by 1.

3. For the 3rd instance of A, if B to <= 0 reset C to 0

I am not comfortable writing code and prefer to use the query builder but do not know how to tackle this rule.

I think that I should introduce X to count the number of times that A appears and create my rules based on that.

eg.

A     X     B     C

a     1      2     1

b     1      1     1

c     1     -2     0

a     2      3     2

c     2      4     1

a     3      0     0

(Assuming I have followed the correct logic as per my rules.

Firstly, I do not know how to count how many times a variable appears in a column.

Secondly, I do not know how to build this query.

Your assistance will be greatly appreciated.
    

3 REPLIES 3
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Hi,

There isn't enough information there to do it right at the moment.  You need to identify a sort order first, i.e. what makes a, B=2 appear prior to the record a, b=3.  

ahtinuS
Fluorite | Level 6

Apologies, there is a sort criteria. There is another variable that must be sorted in ascending order prior to the rules.

eg. SORT TABLE  ABC ON  FIELD XYZ in ascending order

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Pretty straightforward in Base SAS then:

data have;

attrib A format=$1. X B C format=best.;

infile datalines;

input a $ x b c;

datalines;

a     1      2     1

b     1      1     1

c     1     -2     0

a     2      3     2

c     2      4     1

a     3      0     0

;

run;

proc sort data=have;

  by a x;

run;

data inter;

  set have;

  by a;

  retain result;

  if first.a and b > 0 then result=1;

  else do;

    if b > 0 then result=result+1;

    else result=0;

  end;

run;

As for doing it in a query then that is a bit more tricky as there is no retain options.

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 505 views
  • 0 likes
  • 2 in conversation