首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在SAS proc SQL中使用MS SQL窗口函数

如何在SAS proc SQL中使用MS SQL窗口函数
EN

Stack Overflow用户
提问于 2021-03-23 17:21:45
回答 2查看 63关注 0票数 0

嗨,我正在尝试计算客户在这个月支付了多少钱,从下个月减去他们的余额。数据看起来像这样:我想通过7月20日的余额计算6月20日的A111的PaidAmount -6月20日的余额。有人能帮帮忙吗?谢谢

EN

回答 2

Stack Overflow用户

发布于 2021-03-24 00:57:58

这是一个潜在的计算,这通常是通过PROC扩展完成的,但这是在SAS/ETS许可证下进行的,没有多少用户拥有该许可证。另一种选择是将数据与自身合并,将记录偏移一个,这样下一个月的记录就在同一行上。

代码语言:javascript
运行
复制
data want;
merge have have(firstobs=2 rename=balance = next_balance);
by clientID;
PaidAmount = Balance - next_balance;
run;

如果你可以在你的系列中错过几个月,这不是一个好的方法。如果可能,您希望改用SQL进行显式合并。这里假设您的SAS日期也是month。

代码语言:javascript
运行
复制
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;

代码未测试,因为没有提供测试数据(我不会键入您的数据来测试代码)。

票数 0
EN

Stack Overflow用户

发布于 2021-03-24 02:23:04

对于这种情况,没有必要向前看,因为您只需回顾一下就可以创建您想要的输出。

代码语言:javascript
运行
复制
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;

结果:

代码语言:javascript
运行
复制
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          .
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66760336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档