SAS如何筛选保留month变量范围覆盖1-7的对应ID的所有观测
实现思路
核心逻辑是先按ID分组校验是否完整覆盖1-7月,再保留符合条件的ID的全部观测,不需要用IML或者复杂的lag判断,两种常用实现方式如下:
方法1:PROC SQL 单步实现(最简洁)
proc sql; create table work.want as select * from work.have where id in ( select id from work.have where month between 1 and 7 group by id having count(distinct month) = 7 ); quit;
逻辑说明:子查询先筛选出每个ID在1-7月内的去重月份数为7的所有ID,主查询直接保留这些ID的全部观测。如果确认原数据中每个ID的month不存在重复值,可以把count(distinct month)改成count(month),运行效率更高。
方法2:DATA步 + MERGE实现(适合大数据量场景,效率更高)
/* 第一步:生成符合条件的ID列表 */ proc sort data=work.have out=tmp_sorted; by id month; run; data tmp_valid_id; set tmp_sorted; by id; retain cnt 0; if first.id then cnt=0; if month between 1 and 7 then cnt+1; if last.id and cnt=7 then output; keep id; run; /* 第二步:匹配原表保留符合条件ID的全部观测 */ proc sort data=work.have; by id; run; data work.want; merge work.have (in=a) tmp_valid_id (in=b); by id; if b; run;
之前代码的核心问题
- BY语句中没有指定month变量,无法使用
first.month/last.month分组标识 - lag函数是取前一行观测的变量值,无法直接计算整个ID组的统计特征,不适合这个场景的分组判断需求
内容的提问来源于stack exchange,提问作者Pinka
相关产品推荐
相关产品推荐

