【问题标题】:WHERE statement in SAS EG for getting the prior month of a dataset?SAS EG 中的 WHERE 语句用于获取数据集的前一个月?
【发布时间】:2021-12-03 04:06:24
【问题描述】:

这实际上是我想在 SAS EG 的查询生成器中输入的内容。我正在尝试过滤具有以下日期的数据集:

SEP2021
AUG2021
JUL2021
etc…

我正在尝试使用查询生成器通过 WHERE 语句对其进行过滤。我希望表格中只有上个月的结果。所以现在运行它应该给出 SEP2021,下个月运行它会给出 OCT2021,等等……

如何使用WHERE 语句来做到这一点?

【问题讨论】:

  • 该字段是文本字段还是具有日期格式的数字字段?
  • 这是一个文本字段
  • 我已将其转换为日期字段

标签: sql sas query-builder


【解决方案1】:

使用intnx()。假设所有日期都从月初开始:

where date = intnx('month', today(), -1, 'B');

如果他们不这样做:

where intnx('month', date, 0, 'B') = intnx('month', today(), -1, 'B');

【讨论】:

  • 这看起来不错,但不幸的是,我意识到 SEP2021 等日期列的值是字符格式而不是日期格式。我正在查看是否可以在尝试过滤之前在我的 SAS EG 运行中将格式转换为单独的程序,但我正在苦苦挣扎
  • 更新:我已将日期列转换为日期格式。结果现在看起来像这样,并且在输出数据中它们上方有日历徽标:01SEP2021 01AUG2021。我正在尝试您提供的第一个 intnx 函数并且没有错误,但也没有结果。有没有我遗漏的细节?
  • where date=put(intnx('month', today(), -1, 'B'), monyy5.);适用于 SQL 中的行内转换。
【解决方案2】:

您可以使用 INTCK 函数来计算两个日期之间的数字日历间隔。

例子:

data have;
  input datestring $; datalines;
SEP2021
AUG2021
JUL2021
run;

proc sql;
  create table want as
  select * from have
  where intck('month',input(datestring,monyy7.),today()) = 1
;

【讨论】:

    【解决方案3】:

    这是来自 SAS 社区的 KurtBremser 的答案,这对我有用!我没有意识到我将字符值转换成什么格式。 PROC CONTENTS 显示我的值是数字,格式 DTDATE9。

    这里有完整的线程:https://communities.sas.com/t5/SAS-Enterprise-Guide/How-can-PROC-SQL-return-only-results-from-the-previous-month/m-p/774523

    解决方法如下:

    “ 所以它是一个日期时间值,而不是日期。您需要使用 DATEPART 从中提取日期:

    data have;
    input date_column datetime19.;
    format date_column dtdate9.;
    datalines;
    01sep2021:01:02:03
    01oct2021:04:05:06
    ;
    
    proc contents data=have;
    run;
    
    proc sql;
    select *
    from have
    where datepart(date_column) = intnx('month',today(),-1,'b');
    quit;
    

    部分结果:

    #   Variable    Typ Länge   Ausg.Format
    1   date_column Num 8   DTDATE9.
    
    date_column
    01SEP2021
    

    【讨论】:

      猜你喜欢
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多