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

I need to test that a column is monotonic within a group.  In other words that for a given group each subsequent row has an ascending number.  So if id = 100 and there are three rows it will have 1, 2, 3.  With PostgreSQL I would use a window function.  Something like this:

 

CREATE TEMPORARY TABLE foo (
	id integer,
	val integer 
);

INSERT INTO foo VALUES (1, 1), (1, 2), (1, 3), (2, 1), (3, 1), (3, 2);

SELECT
	id,
	CASE
		WHEN LAG(val) OVER (PARTITION BY id) = val - 1 THEN TRUE
		WHEN LAG(val) OVER (PARTITION BY id) IS NULL THEN TRUE
		ELSE FALSE
	END AS passed
FROM foo;

Is there any equivalent function in SAS?  The SAS lag function does not work with group partitions like in SQL. 

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

It is much easier using a data step since SAS will process the records in order.

Do you want to consider the first value for each ID to be PASSED or not?

data want ;
  set have ;
  by id val ;
  passed = dif(val)=1 ;
  if first.id then passed=1 ;
run;

View solution in original post

1 REPLY 1
Tom
Super User Tom
Super User

It is much easier using a data step since SAS will process the records in order.

Do you want to consider the first value for each ID to be PASSED or not?

data want ;
  set have ;
  by id val ;
  passed = dif(val)=1 ;
  if first.id then passed=1 ;
run;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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
  • 1 reply
  • 3040 views
  • 0 likes
  • 2 in conversation