获取每个国家的最后2个观察结果

时间:2016-12-26 17:18:50

标签: sas

我有不同的国家,需要每个国家/地区的最后2次观察

India 200
India 300
India 400
US 1000
US 2000
US 3000
US 4000

我应该 -

India 300
India 400
US 3000
US 4000

2 个答案:

答案 0 :(得分:1)

可能会有一个更短的方式,但这将有效:

data have;
country = "INDIA";
pop = 200;
output;
country = "INDIA";
pop = 500;
output;
country = "INDIA";
pop = 300;
output;
country = "US";
pop = 1200;
output;
country = "US";
pop = 1400;
output;
country = "US";
pop = 900;
output;
country = "US";
pop = 1500;
output;
country = "INDIA";
pop = 700;
output;
run;

proc sort data=have;
by country descending pop;
run;

data have;
set have;
by country;
retain cnt;
if first.country then cnt = 1;
else cnt = cnt + 1;
run;

proc sql noprint;
create table want as
select country,pop from have
where cnt < 3;quit;

答案 1 :(得分:0)

这假设您的数据按国家/地区分组。我估计你会把这称为合并某种类型。

data country;
   input country $ x;
   cards;
India 200
India 300
India 400
NZ 4567
US 1000
US 2000
US 3000
US 4000
;;;;
   run;
data last2;
   merge country country(firstobs=3 keep=country rename=(country=z));
   if country ne z;
   run;
proc print;
   run;

enter image description here