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-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

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.

SAS Training: Just a Click Away

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

Browse our catalog!

Discussion stats
  • 1 reply
  • 3807 views
  • 0 likes
  • 2 in conversation