You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PROC SQL中编写宏以自动获取并使用当月第一天和最后一天

SAS PROC SQL自动获取当月首尾日期实现方案

方案1:直接定义宏变量(适合固定取当月的场景)

直接通过SAS自带的INTNX函数计算当月首尾日期,定义为全局宏变量即可直接调用:

/* 计算当月第一天(返回SAS原生日期值,可直接和日期型字段对比) */
%let month_first = %sysfunc(intnx(month, %sysfunc(today()), 0, B));
/* 计算当月最后一天 */
%let month_last = %sysfunc(intnx(month, %sysfunc(today()), 0, E));

/* 若需要和你原代码一样输出yymmn6.格式的6位年月数值,改用下面的定义即可 */
* %let month_first = %sysfunc(putn(%sysfunc(intnx(month, %sysfunc(today()), 0, B)), yymmn6.));
* %let month_last = %sysfunc(putn(%sysfunc(intnx(month, %sysfunc(today()), 0, E)), yymmn6.));

在PROC SQL中使用示例:

proc sql;
    select * from 你的表名 t1
    where t1.DATE between &month_first. and &month_last.
        and _dly. between t2.data_from and t2.data_to 
        and &gv_date_dly. between t3.data_from and t3.data_to 
        and t3.obj_code not in ('G07','N06','N07');
quit;

方案2:封装为可复用宏(支持自定义月份、输出变量名)

如果需要灵活指定查询月份、或者要和你原有&thismonth变量联动,可以封装为通用宏:

%macro get_month_range(month=, out_prefix=month);
    /* 参数说明:
    month: 输入参考年月,默认取当月,支持SAS日期值或yymmn6.格式的6位年月数值
    out_prefix: 输出宏变量前缀,默认值为month,调用后生成&out_prefix._first、&out_prefix._last两个宏变量
    */
    %if &month. = %then %let month = %sysfunc(today());
    %else %if %length(&month.)=6 %then %let month = %sysfunc(inputn(&month., yymmn6.));

    %global &out_prefix._first &out_prefix._last;
    %let &out_prefix._first = %sysfunc(intnx(month, &month., 0, B));
    %let &out_prefix._last = %sysfunc(intnx(month, &month., 0, E));
%mend;

调用方法:

  • 取当月范围:%get_month_range(),调用后直接使用&month_first、&month_last即可
  • 和你原有&thismonth变量联动:%get_month_range(month=&thismonth),会自动计算&thismonth对应年月的首尾日期
  • 自定义输出变量前缀:%get_month_range(out_prefix=this_month),调用后使用&this_month_first、&this_month_last即可

注意:如果你的表中DATE字段存储为yymmn6.格式的6位数值,只需在宏定义的intnx函数外层套putn(, yymmn6.)做格式转换,保证变量和字段格式匹配即可避免筛选错误。

内容的提问来源于stack exchange,提问作者Przemek Dabek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:06:04