【问题标题】:How to use MS SQL window function in SAS proc SQL如何在 SAS proc SQL 中使用 MS SQL 窗口函数
【发布时间】:2021-03-24 02:23:04
【问题描述】:

您好,我正在尝试通过从下个月减去他们的余额来计算客户当月支付的金额。 数据如下所示:我想通过 7 月 20 日的余额 - 6 月 20 日的余额来计算 20 年 6 月 A111 的 PaidAmount。有人可以帮忙吗?谢谢

【问题讨论】:

  • 请以文字形式发布数据,而不是照片。从图片编码非常困难。

标签: sas


【解决方案1】:

这是寻找一个 LEAD 计算,通常通过 PROC EXPAND 完成,但这是在 SAS/ETS 许可下,没有多少用户拥有。另一种选择是将数据与其自身合并,将记录偏移一个,以便下个月的记录在同一行。

data want;
merge have have(firstobs=2 rename=balance = next_balance);
by clientID;
PaidAmount = Balance - next_balance;
run;

如果您可能会在系列中错过几个月,这不是一个好方法。如果可能的话,您想改为使用 SQL 进行显式合并。这假设您也有月份作为 SAS 日期。

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;

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

【讨论】:

    【解决方案2】:

    对于这种情况,无需向前看,因为您只需向后看即可创建所需的输出。

    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          .
    

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多