[英]Select top 3 observations based upon multiple fields in SAS?
我有一个非常大的SAS数据集,其中包含一些记录,我想根据多个字段求和前3条记录。
数据示例:
假设数据已正确排序,即按Ref,Date1(desc),Time(desc),Date2(Desc)排序。 数据集中不存在“求和”字段(请参见下文)。
使用SAS,我需要为Date2的每个实例求和每个引用的前3个最近值(基于Date1和时间)。 在示例数据中,“求和”字段是需要对数据进行求和的方式,即将所有1和2求和,等等。
不好意思的解释很抱歉,我已经尝试了几天了,但没有成功!
非常感谢。
这应该可以解决问题。 您需要使用通过by
语句启用的by
组处理。 然后,您可以使用第first.
last.
表示何时到达各组的开始或结束的符号。 retain
语句告知sas哪些变量应记住各观察值。
样本数据:
data tmp;
informat date1 date2 ddmmyy10.;
input ref
date1
date2
time
value
;
datalines;
11 03/01/2014 01/01/2014 9 345
11 03/01/2014 01/01/2014 8 322
11 03/01/2014 01/01/2014 7 6546
11 01/01/2014 31/12/2013 6 34
11 01/01/2014 31/12/2013 5 33
22 02/01/2014 01/01/2014 4 234
22 02/01/2014 01/01/2014 3 66
22 01/01/2014 01/01/2014 2 234
33 01/01/2014 01/01/2014 1 2
33 01/01/2014 31/12/2014 0 45
;
run;
然后确保数据正确排序,以便我们可以使用按组处理:
proc sort data=tmp;
by ref date1 date2 descending time;
run;
因为sum()
语句仅在计数器<= 3时才累加值,所以您将获得每个分组的前3个值的总和。 当到达组的末尾时,将输出一条记录。
data tmp2;
set tmp;
by ref date1 date2;
retain counter total .;
if first.date2 then do;
total = 0;
counter = 1;
end;
if counter le 3 then do;
total = sum(total,value);
end;
if last.ref or last.date1 or last.date2 then do;
output;
end;
counter = counter+1;
run;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.