嗨,我正在尝试计算客户在这个月支付了多少钱,从下个月减去他们的余额。数据看起来像这样:我想通过7月20日的余额计算6月20日的A111的PaidAmount -6月20日的余额。有人能帮帮忙吗?谢谢
发布于 2021-03-24 00:57:58
这是一个潜在的计算,这通常是通过PROC扩展完成的,但这是在SAS/ETS许可证下进行的,没有多少用户拥有该许可证。另一种选择是将数据与自身合并,将记录偏移一个,这样下一个月的记录就在同一行上。
data want;
merge have have(firstobs=2 rename=balance = next_balance);
by clientID;
PaidAmount = Balance - next_balance;
run;
如果你可以在你的系列中错过几个月,这不是一个好的方法。如果可能,您希望改用SQL进行显式合并。这里假设您的SAS日期也是month。
proc sql;
create table want as
select t1.*, t1.balance - t2.balance as paidAmount
from have as t1
left join have as t2
on t1.clientID = t2.ClientID
/*joins current month with next month*/
and intnx('month', t1.month, 0, 'b') = intnx('month', t2.month, 1, 'b');
quit;
代码未测试,因为没有提供测试数据(我不会键入您的数据来测试代码)。
发布于 2021-03-24 02:23:04
对于这种情况,没有必要向前看,因为您只需回顾一下就可以创建您想要的输出。
data have;
input id date balance ;
informat date yymmdd10.;
format date yymmdd10.;
cards;
1 2020-06-01 10000
1 2020-07-01 8000
1 2020-08-01 5000
2 2020-06-01 10000
2 2020-07-01 8000
3 2020-08-01 5000
;
data want;
set have ;
by id date;
lag_date=lag(date);
format lag_date yymmdd10.;
lag_balance=lag(balance);
payment = lag_balance - balance ;
if not first.id then output;
if last.id then do;
payment=.;
lag_balance=balance;
lag_date=date;
output;
end;
drop date balance;
rename lag_date = date lag_balance=balance;
run;
proc print;
run;
结果:
Obs id date balance payment
1 1 2020-06-01 10000 2000
2 1 2020-07-01 8000 3000
3 1 2020-08-01 5000 .
4 2 2020-06-01 10000 2000
5 2 2020-07-01 8000 .
6 3 2020-08-01 5000 .
https://stackoverflow.com/questions/66760336
复制相似问题