【问题标题】:SAS EG: Extracting Month from Today() for use in IF statementSAS EG:从 Today() 中提取月份以用于 IF 语句
【发布时间】:2020-10-14 17:10:54
【问题描述】:

对 SAS 比较陌生,正在寻求有关使用日期函数的帮助。

我正在使用 Today()-x 设置日期并使其可用于查看历史数据(很少见,但值得包括)并尝试围绕它编写一个 IF 语句,因为我需要对财政年度结束。

我的代码如下:

%macro RunDate_Variables;
%global rep_month repdt prevdt;

data _null_;

    rundate = today()-0;
    runmonth = Month(rundate);

   %if runmonth eq 04
   %then %do;
   ReportDate = MDY(4, 4, Year(rundate);
   PrevReportDate = intnx('Month', ReportDate,-2,'e');
   %end;
   %else %if runmonth eq 05;
   %then %do;
   ReportDate = intnx('Month', rundate,-1,'e');
   PrevReportDate = iMDY(4, 4, Year(rundate));
   %end;
   %else %do;
   ReportDate = intnx('Month', rundate,-1,'e');
   ReportDate = intnx('Month', ReportDate,-1,'e');
   %end;


   call symputx('rep_month', put(ReportDate, MONYY7.));
   call symputx('repdt', put(ReportDate, yymmddN8.));
   call symputx('prevdt', put(PrevReportDate, yymmddn8.));

run;
%mend;
%RunDate_Variables;

不幸的是,runmonth 似乎并没有像我希望的那样做,因此在宏中没有按预期解决。

最终,我正在寻找的是代码来识别代码何时在 4 月运行,并将 ReportingDate 设置为 4 月 4 日(财政年度结束)和 PrevReportingDate 为 2 月 28 日(或 29 日),以及当代码在 5 月运行时,将 ReportingDate 设置为 4 月 30 日,将 PrevReportingDate 设置为 4 月 4 日。

代码不需要在 3 月 31 日至 4 月 4 日期间在空间中运行,因此在该空间中将其解析到 4 月 4 日将不是问题。

任何建议表示赞赏。代码不需要坚持我尝试过的格式,唯一需要保持不变的是变量名称 rep_month、repdt 和 prevdt,因为这些是我选择项目时在整个代码中使用的名称。

编辑:我已经设法在数据步骤之外使用手动调整的标志并更改 IF 条件来使这个想法起作用,但问题是它需要两个标志(一个用于 4 月,一个用于 5 月) ,或者从标志中读取两个单独的输入(同样,一个识别四月,另一个识别五月)。虽然这可行,但我仍然想研究完全自动化的可能性,因为 FYE 是一个容易记住更改标志的时间,但在 FYE 之后的一个月内更改标志可能不太令人难忘。

谢谢。

【问题讨论】:

  • 您的宏 %IF 语句将 8 个字符串 runmonth 与两个字符串 04 进行比较。那永远不会是真的。您是否打算改用 IF 语句?

标签: sas enterprise-guide


【解决方案1】:

您无法使用宏代码检查数据变量的值,您的 %IF 语句只是将常量字符串 runmonth 与常量字符串 04 进行比较。他们永远不会平等。

我在这里看不到任何需要任何宏逻辑的东西,但如果你想多次调用同一个数据步骤,你仍然可以保留宏定义。

data _null_;
  rundate = today()-0;
  runmonth = Month(rundate);
  if runmonth eq 04 then do;
    ReportDate = MDY(4, 4, Year(rundate);
    PrevReportDate = intnx('Month', ReportDate,-2,'e');
  end;
  else if runmonth eq 05 then do;
    ReportDate = intnx('Month', rundate,-1,'e');
    PrevReportDate = MDY(4, 4, Year(rundate));
  end;
  else do;
    ReportDate = intnx('Month', rundate,-1,'e');
    PrevReportDate = intnx('Month', ReportDate,-1,'e');
  end;
  call symputx('rep_month', put(ReportDate, MONYY7.),'g');
  call symputx('repdt', put(ReportDate, yymmddN8.),'g');
  call symputx('prevdt', put(PrevReportDate, yymmddn8.),'g');
run;

【讨论】:

  • 太棒了,谢谢。将它包装在宏中的想法来自我们现有的一些代码,这些代码是由有经验的人编写的,所以我只是复制了他们的做法。我想有一个原因他们将他们的包裹在一个宏中,这在我的代码中并不明显,但是下次他们可用时我将不得不质疑它,以便我可以学习。我已经在我的代码中实现了更改并通过它运行了一些测试日期,它似乎运行良好。 :)
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 2011-08-15
  • 2022-07-18
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多