想要拉当前月-2个月

时间:2019-06-14 15:54:31

标签: sql sas

我想通过intnx函数尝试在SAS中提取current_month - months。但这对我不起作用。

DATA
 input_file
 ;
 input
  @1 DHQ_ID             5.
  @7 AS_OF_DT           DATE9.
  @22 CUST_THIS_MONTH_SPEND  7.5
  ;
FORMAT    AS_OF_DT       DATE9.
   ;
DATALINES;
10970 01OCT2014 0
10970 01NOV2014 0
10970 01JAN2015 0
10970 01FEB2015 0
10970 01MAR2015 0
10970 01APR2015 20
10970 01MAY2015 800
;
RUN;

%LET date = "01FEB2015"d;

proc sql;
    create table master_zero as select 
        dhq_id, 
        sum(case  when cust_this_month_spend <= 0 OR 
                  (INTNX('month',&date.,-2)) IS NULL
       then 1 else 0 end)as cnt_zero 
    from input_file
        where 
        as_of_dt between intnx('month',&date.,-2) and &date. 
        group by dhq_id 
        order by dhq_id;
quit;


data master_zero2 (drop = cnt_zero);
    set master_zero (where = (cnt_zero = 3));
    format dt date9.;
    dt = &date.;
run;

结果:

DHQ_ID  CNT_ZERO dt 
10970   2        01DEC2014

1 个答案:

答案 0 :(得分:0)

您显示的示例代码可能无法正确阅读CUST_THIS_MONTH_SPEND

@17 CUST_THIS_MONTH_SPEND  best7.

代替

@22 CUST_THIS_MONTH_SPEND  7.5

您可以算出每个组的月份数,0是支出,也可以是目标月之前3个月内未记录的支出,如下所示:

  • 将行限制为3个月前的行
  • 求和逻辑评估以计算已知零
  • 通过从预期行(count(*))中减去存在的行数(3)来计数不存在的月份

示例:

DATA have;
 format groupid 8. as_of_dt date9.;
 input groupid as_of_dt DATE9. spending; DATALINES;
10970 01OCT2014 0
10970 01NOV2014 0
10970 01JAN2015 0
10970 01FEB2015 0
10970 01MAR2015 0
10970 01APR2015 20
10970 01MAY2015 800
;
RUN;

%LET month = "01FEB2015"d;

proc sql;
  create table want as
  select 
    groupid,
    sum(spending = 0) + 3 - count(*) as zeromissingCount,
    &date as ending_month format=monyy7.
  from have
  where intck('month', &date, as_of_dt) between -2 and 0
  group by groupid
  ;