导读: 最近在数据处理和分析过程中,遇到一个问题:用户A在不同的月份具有两个分数,如何使用SAS来汇总这个分数使得其变成一行中的两个字段。
问题实例:
xaccount | score | score_date |
---|---|---|
1 | 900 | 20200731 |
1 | 800 | 20200831 |
转化为:
xaccount | score_first | score_last |
---|---|---|
1 | 900 | 800 |
解法: 通过SAS的retain+first+last实现合并
data a;
input xaccount score score_date;
cards;
1 900 20200731
1 800 20200831
;
run;
proc sort data=a;by xaccount;run;
data b;
set a;
by xaccount;
retain score_first score_last;
if first.xaccount then score_first=score;
if last.xaccount then score_last=score;
if last.xaccount then output;
drop score score_date; /*此处可以去掉不需要保留的旧字段*/
run;
如果有多条数据,都要进行汇合,那么可以考虑使用多个retain变量或者循环来解决。如果要在多个记录中选取特殊的记录进行汇合,建议先对需要的记录标记flag,再使用if条件来进行锁定和汇合。