如何使用sas sql获取第n个最大的数字



以下是数据:

data bonus1;
infile cards;
input ID Amt;
cards;
1 123
2 748
3 355
4 3223
5 124
6 11
;
run;

我想获得第二大amt。我已经完成了,我的代码是:

proc sql;
create table bonus1_ans as
select max(amt)
from bonus1
where amt not in 
(select max(amt) from bonus1);
quit;

当我只想获得第二个最大值时,这种结构是有效的,但如果我想获得第n个最大值,它是无效的,因为嵌套的查询太多了。

我尝试了一些更好的结构,但SASSQL似乎不支持limit、fetch和top,所以我的尝试失败了。

你能帮我做一个更通用的代码吗?

然后走出SQL,同时考虑关系。

data bonus1;
infile cards;
input ID Amt;
cards;
1 123
2 748
3 355
4 3223
5 124
6 11
;
run;
*second largest value;
proc sort data=bonus1; by descending amt; run;
data want;
set bonus1 (firstobs=2 obs=2);
run;
*but what about ties;
data bonus1;
infile cards;
input ID Amt;
cards;
1 123
2 748
3 355
4 3223
5 3223
6 11
;
run;
*second largest value;
proc sort data=bonus1; by descending amt; run;
data want_ties;
set bonus1;
by descending amt;
retain count 0;
if first.amt then count+1;
if count=2 then do;
output;
stop;
end;
run;
*Generates Top/Botton N Values;
ods select none;;
ods output extremevalues=want_uni;
proc univariate data=bonus1 nextrval=2;
var AMT;
run;
ods select all;
proc print data=want_uni;
run;

Proc RANK将计算第k个序列位置。您需要SQL是有原因的吗?

proc rank data=bonus1 descending out=amt_rank(where=(amt_n=4));
var amt;
ranks amt_n;
run;

在SASSQL中,有一个解决方案,尽管它使用了一个不受支持的未记录函数monotonic()。它还需要创建一个表,因为order不能在最后一条语句之外的任何地方使用,并且在视图中也不能正常工作。

data bonus1;
infile cards;
input ID Amt;
cards;
1 123
2 748
3 355
4 3223
5 124
6 11
;
run;
proc sql;
create table t_bonus_ord as 
select id, amt
from bonus1
order by amt desc
;
select id, amt
from t_bonus_ord        
where monotonic() =4
;
quit;

monotonic只返回1,2,3,4等,可以类似于数据步骤中的_n_变量使用,但只能在有限的情况下使用,如果您想要可靠的结果,通常是从数据集中直接选择。

不过,我想说的是,我更喜欢Reeza的各种选择——SASSQL能够做到这一点,但也有更好的方法。

最新更新