最近5个转发中的特定交易数量

时间:2016-02-15 13:16:33

标签: sql sas proc-sql datastep

我想写sas代码(proc-sql)。问题是如何创建变量VP_Trans(在下表中)。下表是指某段时间内的客户交易。 我想计算一下客户基于他最近5笔交易的VP交易数量。包括第五项交易 例如客户1根据1.2.-11.2之间的交易计算了5个VP交易。

+---------+-------------+-----------+----------+
| cust id | Trans Dates | TransType | Vp_Trans |
+---------+-------------+-----------+----------+
|       1 | 2015-02-01  | VP        | NA       |
|       1 | 2015-02-03  | Vp        | NA       |
|       1 | 2015-02-06  | VP        | NA       |
|       1 | 2015-02-06  | Vp        | NA       |
|       1 | 2015-02-11  | Vp        | 5        |
|       1 | 2015-02-13  | MG        | 4        |
|       1 | 2015-02-17  | Vp        | 4        |
|       1 | 2015-02-18  | mg        | 3        |
|       1 | 2015-02-19  | mg        | 2        |
|       1 | 2015-02-20  | mg        | 1        |
|       1 | 2015-02-21  | vp        | 2        |
|       2 | 2015-02-01  | VP        | NA       |
|       2 | 2015-02-03  | mg        | NA       |
|       2 | 2015-02-06  | mg        | NA       |
|       2 | 2015-02-06  | Vp        | NA       |
|       2 | 2015-02-11  | Vp        | 3        |
|       2 | 2015-02-13  | MG        | 2        |
|       2 | 2015-02-17  | Vp        | 3        |
|       2 | 2015-02-18  | mg        | 3        |
|       2 | 2015-02-19  | mg        | 2        |
|       2 | 2015-02-20  | mg        | 1        |
|       2 | 2015-02-21  | mg        | 1        |
|       2 | 2015-02-22  | mg        | 0        |
+---------+-------------+-----------+----------+

2 个答案:

答案 0 :(得分:0)

如果您的DBMS支持Windowed Aggregates,那么它只是一个简单的移动计数:

select
   cust_id, Trans_Dates, TransType,
   count(case when TransType = 'VP' then 1 end)
   over (partition bycust_id
         order by Trans_Dates
         rows 4 preceding) as Vp_Trans
from tab

答案 1 :(得分:0)

使用5元素数组来跟踪type =' VP'的检查。使用MOD()函数实现环绕索引。以下是您的示例数据:

data have ;
 input id Date Type $ Expected ;
 informat date yymmdd10.;
 format date yymmdd10.;
cards;
 1 2015-02-01 VP .
 1 2015-02-03 Vp .
 1 2015-02-06 VP .
 1 2015-02-06 Vp .
 1 2015-02-11 Vp 5
 1 2015-02-13 MG 4
 1 2015-02-17 Vp 4
 1 2015-02-18 mg 3
 1 2015-02-19 mg 2
 1 2015-02-20 mg 1
 1 2015-02-21 vp 2
 2 2015-02-01 VP .
 2 2015-02-03 mg .
 2 2015-02-06 mg .
 2 2015-02-06 Vp .
 2 2015-02-11 Vp 3
 2 2015-02-13 MG 2
 2 2015-02-17 Vp 3
 2 2015-02-18 mg 3
 2 2015-02-19 mg 2
 2 2015-02-20 mg 1
 2 2015-02-21 mg 1
 2 2015-02-22 mg 0
;;;;

以下是计算VP_TRANS的数据步骤。

data want ;
   do n=1 by 1 until (last.id);
      set have ;
      by id date ;
      array flags (5) ;
      flags(mod(n,5)+1)= upcase(type)='VP';
      if n>= 5 then VP_trans=sum(of flags(*));
      output;
  end;
  drop flags: ;
run;
proc print; run;

enter image description here