SAS-如何计算某个月份之前10年的观察次数

Nea*_*801 0 sas rolling-computation

我有一个包含两个变量的示例:ID 和 ym。ID id 是指每个交易者的特定 ID,ym 是指年月变量。我想创建一个变量来显示t月之前 10 年期间的年数,如下图所示。

ID  ym  Want
1   200101  0
1   200301  1
1   200401  2
1   200501  3
1   200601  4
1   200801  5
1   201201  5
1   201501  4
2   200001  0
2   200203  1
2   200401  2
2   200506  3
Run Code Online (Sandbox Code Playgroud)

我尝试使用by函数并fisrt.id计算数字。

data want;
set have;
want+1;
by id;
if first.id then want=1;
run;
Run Code Online (Sandbox Code Playgroud)

但是,ym 中的年份不是连续的。当时间间隔大于 10 年时,此方法不起作用。尽管我假设我需要计算滚动窗口(10 年)中的年数,但我不确定如何实现。请给我一些建议。谢谢。

Tom*_*Tom 5

只需在 SQL 中进行自联接即可。通过您对 YM 的编码,很容易进行一年的倍数间隔,但很难进行其他间隔。

proc sql;
create table want as 
  select a.id,a.ym,count(b.ym) as want 
  from have a 
   left join have b
   on a.id = b.id
   and (a.ym - 1000) <= b.ym < a.ym
  group by a.id,a.ym
  order by a.id,a.ym
;
quit;
Run Code Online (Sandbox Code Playgroud)