从多个观察sas计算一个新的字段

时间:2016-03-14 11:23:38

标签: sas

我很难在SAS中找到如何最好地处理样本数据中的情景" alex"在2015年有两个订单,因此我想要一个新的列显示他的状态="活跃"

任何有用的提示让我走上正轨?感谢

 ID     first_order      Order
 alex      01/01/2013     23/01/2015
 alex      01/01/2013     23/01/2015 
 alex      01/01/2013      03/04/2013

1 个答案:

答案 0 :(得分:1)

在这个例子中,我们假设Alex在2013年下了一个订单,在2015年下了另一个订单.Bob在2013年只下了一个订单。让我们创建一些数据:

data have;
    format id $4. first_order Order date9.;
    id = 'Alex'; first_order = '01JAN2013'd; Order = '23JAN2015'd; output;
    id = 'Alex'; first_order = '01JAN2013'd; Order = '03APR2013'd; output;
    id = 'Bob';  first_order = '01JAN2013'd; Order = '01JAN2013'd; output;
run;

以下宏可用于推导任何特定年份的客户状态。

%macro Active(year=);

proc sql;
    create table CustomerStatus as
    select id,
           case when max(year(Order)) = &year then 'Active' 
           else 'Inactive' end as Status_in_&year length=8 
    from have
    group by id
    order by id;

    create table want as
    select have.id, have.first_order, have.Order, CustomerStatus.Status_in_&year
    from have inner join CustomerStatus on have.id = CustomerStatus.id
    order by CustomerStatus.id;
quit;

%mend Active;

%Active(year=2015);

在表CustomerStatus中,我们获得所有客户的最新订单年份。如果这等于订单的年份,则客户状态为“活动”。最后,状态与Orders表连接。