BookmarkSubscribeRSS Feed
georgel
Quartz | Level 8

Hi all, 

I would like to keep the first two observations ordered by date by group using sql in one step 

proc sql;
     select *, ROW_NUMBER()
	 from test_sql
	 where ROW_NUMBER<=2
	   order by cusip date;
quit;

The above does not work

Many thanks in advance

Regards

George

2 REPLIES 2
Reeza
Super User

ROW_NUMBER() isn't valid in SAS SQL, I think that's MS SQL?

All DBs do this one a bit differently, Oracle is ROWNUM for example.

 

Have you tried using the MONOTONIC() function or using the OBS= data set option? 

Note that you were also missing a comma in the ORDER BY clause.

 

proc sql;
    create table want(obs=2) as
     select * 
	 from test_sql
	   order by cusip, date;
quit;
proc sql;

     select * , monotonic() as rowNum
	 from test_sql
         where calculated rowNum <=2
	   order by cusip, date;
quit;

@georgel wrote:

Hi all, 

I would like to keep the first two observations ordered by date by group using sql in one step 

proc sql;
     select *, ROW_NUMBER()
	 from test_sql
	 where ROW_NUMBER<=2
	   order by cusip date;
quit;

The above does not work

Many thanks in advance

Regards

George


 

ChrisNZ
Tourmaline | Level 20

Note that SQL does not guarantee that rows will be processed in the table order.

If you read a single table and use option proc sql nothreads,  it should still happen though.

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
  • 2 replies
  • 836 views
  • 2 likes
  • 3 in conversation