The automatic variable _N_ in DATA step processing counts the number of times the DATA step begins to iterate. It’s very useful when you need the iteration number from the DATA step.
Since PROC SQL uses a relational database concept that is different from the DATA step, we can’t get the iteration number from the PROC SQL procedure. An undocumented function, MONOTONIC( ), in PROC SQL that can generate very similar result as the _N_ in DATA step. Look at the following example:
Example 1:
proc sql;
select monotonic() as rowno, *
from testdata2
where monotonic() le 10;
quit;
The above program will generate the output:
rowno id y
-----------------------------
1 1 66
2 2 32
3 3 10
4 4 24
5 5 50
6 6 73
7 7 40
8 8 45
9 9 88
10 10 65
So we can treat the MONOTONIC( ) function in PROC SQL as the _N_ in DATA step if we need to use the row number of the table in PROC SQL.
data one;
input region $ vendorname $ amount carname $;
cards;
east a 2 kk
east a 2 tt
east a 2 ss
east a 2 ta
east a 2 lk
east a 2 oo
east a 2 pp
west b 4 op
west b 4 xp
west b 4 wp
west b 4 up
west b 4 lp
west b 4 oi
south n 9 mc
south n 9 ci
;
proc sql;
create table temp as
select region, count (*) as count
from one
group by region
order by region desc;
proc sql;
create table temp2 as
select * from temp
where monotonic() <=2;
quit;
(monotonic() give the observation number you want, where monotonic()<=20 chooses the first 20 observations from table temp)