在SAS中移除ID相同且Match字段为空的重复记录
SAS 移除ID重复且Match为空的记录方案
以下几种方法可实现需求:保留每个ID下Match非空的记录,删除同一ID下Match为空的重复行;若某ID所有记录的Match均为空,则保留其中一条。
方法1:PROC SORT 组合去重(高效简洁)
通过排序将Match非空的记录排在同ID组最前面,再按ID去重保留第一条:
/* 第一步:按ID分组,将Match非空的记录置于每组首位 */ proc sort data=your_input_data out=temp_sorted; by id descending match; /* SAS中空值优先级最低,降序后非空值靠前 */ run; /* 第二步:按ID去重,自动保留每组第一条(即Match非空的记录) */ proc sort data=temp_sorted out=your_output_data nodupkey; by id; run;
- 优势:代码短,处理大数据集效率高
- 说明:若某ID全是Match为空,会保留该ID的其中一条记录
方法2:DATA步 BY组处理(灵活可控)
通过BY组标记需保留的记录,逻辑更清晰:
data your_output_data; set your_input_data; by id; retain keep_group 0; /* 进入新ID组时重置标记 */ if first.id then do; keep_group = 0; /* 标记当前组是否存在Match非空的记录 */ if not missing(match) then keep_group = 1; end; /* 保留规则:组内有非空Match则留对应记录,否则只留组内第一条 */ if keep_group = 1 or (not missing(match)) then output; else if first.id then output; run;
- 优势:可自定义保留规则,比如需保留多条非空Match记录时,只需调整条件
missing()函数兼容字符型和数值型Match字段,通用性强
方法3:PROC SQL 子查询组合
用SQL逻辑拆分需求,适合熟悉SQL语法的用户:
proc sql; create table your_output_data as -- 第一部分:保留所有Match非空的记录 select * from your_input_data where not missing(match) union all -- 第二部分:保留无有效Match的ID的单条记录 select * from your_input_data where id not in (select distinct id from your_input_data where not missing(match)) group by id having monotonic() = 1; quit;
- 优势:逻辑直观,无需中间数据集
- 说明:
monotonic()是SAS SQL非官方函数,也可用min(_n_)替代实现取每组第一条
内容的提问来源于stack exchange,提问作者unluckyforsome
相关产品推荐
相关产品推荐

