You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何标记同一ID与日期下结果不同的SAS观测值?

解决方案

方法1:PROC SQL 简洁实现

通过分组统计每个ID+Dt组合下result的不同取值数量,直接生成标记变量:

proc sql;
    create table test_marked as
    select t.*, 
           case when count(distinct result) > 1 then 1 else 0 end as has_diff_result
    from test t
    group by ID, Dt
    order by ID, Dt;
quit;

生成的has_diff_result变量中,1代表该ID+Dt组合内存在不同的result值,0代表取值完全一致。

方法2:DATA步 BY组处理

先排序保证分组逻辑正常,再通过BY组计算每组的最小/最大result值,判断是否存在差异:

/* 先按ID和Dt排序,确保BY组逻辑生效 */
proc sort data=test;
    by ID Dt;
run;

data test_marked;
    set test;
    by ID Dt;
    /* 保留当前组的最小、最大result值 */
    retain min_result max_result;
    if first.Dt then do;
        min_result = result;
        max_result = result;
    end;
    else do;
        min_result = min(min_result, result);
        max_result = max(max_result, result);
    end;
    /* 标记差异:最小≠最大则为1 */
    has_diff_result = (min_result ne max_result);
    /* 组结束后清空临时变量,避免干扰下一组 */
    if last.Dt then call missing(min_result, max_result);
run;

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:42:02