使用SAS下的SQL,仍然有几种可选的做法来生成行号。
1. 连接到Oracle,然后将SQL交给Oracle执行,Oracle的SQL标准不同于SAS的ANSI 1992,row_number()函数受到支持;
2. 使用内置monotonic()函数;
- proc sql noprint;
- create table class as
- select *, monotonic() as monotonic from sashelp.class
- order by sex, name
- ;
- quit;
复制代码
3. 使用SAS函数resolve(),并利用SAS逐行处理数据的特点;
- %let i=1;
- create table class2 as
- select *, resolve('&i %let i=%eval(&i+1)') as rownum from sashelp.class
- order by sex, name
- ;
复制代码
4. 利用SQL的子查询;
- create table class3 as
- select *, (select sum(catx('',b.sex,b.name)<=catx('',a.sex,a.name)) from sashelp.class b) as rownum
- from sashelp.class as a
- order by sex, name
- ;
复制代码
应当说明,方法2与3是在读入原数据时生成行号,方法4则是在生成新数据时生成行号,因此结果有所不同。
对方法4略加变化,可以得到符合题意的示例程序:
- create table class4 as
- select *, (select sum(b.name<=a.name) from sashelp.class b where a.sex=b.sex) as rownum
- from sashelp.class as a
- order by sex, name
- ;
复制代码