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

SAS如何实现分组多行数据计算:学生期末成绩核算

SAS实现学生期末成绩计算方案

假设你的原始数据集命名为homework_scores,包含3个核心字段:

  • student_id:学生唯一ID
  • hw_id:作业编号,取值为1/2/3/4/5对应5次作业
  • score:对应作业的分数,缺失值为SAS默认的.

方案1:长表转宽表+数据步计算(逻辑直观易调试)

/* 第一步:将按作业分行的长表转为每个学生1行的宽表 */
proc transpose data=homework_scores out=hw_wide prefix=hw_score_;
    by student_id;
    id hw_id;
    var score;
run;

/* 第二步:按规则计算期末成绩 */
data final_score;
    set hw_wide;
    /* 统计5次作业的缺失值总数 */
    missing_cnt = nmiss(hw_score_1, hw_score_2, hw_score_3, hw_score_4, hw_score_5);
    if missing_cnt > 1 then final_grade = .;
    else do;
        /* 计算前4次作业的平均值,自动跳过缺失值 */
        avg_first4 = mean(hw_score_1, hw_score_2, hw_score_3, hw_score_4);
        final_grade = 0.7 * avg_first4 + 0.3 * hw_score_5;
    end;
    /* 可选:保留需要输出的字段 */
    keep student_id final_grade;
run;

方案2:PROC SQL直接聚合计算(无需转置,代码更简洁)

proc sql;
    create table final_score as
    select 
        student_id,
        case 
            when nmiss(score) > 1 then .
            else 0.7 * mean(case when hw_id in (1,2,3,4) then score else . end) + 0.3 * max(case when hw_id=5 then score else . end)
        end as final_grade
    from homework_scores
    group by student_id;
quit;

逻辑说明:nmiss(score)按学生分组统计5次作业的缺失数;分组计算前4次作业均值时,通过case when过滤出作业编号1-4的分数,mean函数自动忽略缺失值;第5次作业分数用max/min取出分组内对应的值即可。

内容的提问来源于stack exchange,提问作者linda.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:12:01