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

在SAS中为数据集工作日记录匹配对应月份最后一个工作日

Solution to Match Last Weekday of the Month in SAS

First, let's break down what we need to do: convert your numeric date values to SAS dates, find the last day of the corresponding month, then adjust that date to the nearest preceding weekday (since weekends aren't present in your dataset). Here's a straightforward, efficient way to do this in a single SAS data step:

data want;
    set have;
    /* Convert numeric YYYYMMDD date to SAS date value */
    sas_date = input(put(Date, 8.), yymmdd8.);
    
    /* Calculate the last day of the month for the current date */
    last_day_month = intnx('month', sas_date, 0, 'end');
    
    /* Adjust to the last weekday (exclude Saturdays and Sundays) */
    last_weekday = last_day_month - (weekday(last_day_month) = 1)*2 - (weekday(last_day_month) = 7)*1;
    
    /* Convert the last weekday back to numeric YYYYMMDD format */
    Enddate = input(put(last_weekday, yymmddn8.), 8.);
    
    /* Clean up intermediate variables (optional but recommended) */
    drop sas_date last_day_month last_weekday;
    
    /* Optional: Format variables for easier reading */
    format Date Enddate yymmddn8.;
run;

Step-by-Step Explanation:

  • Convert to SAS Date: The input(put(Date,8.), yymmdd8.) converts your numeric Date (e.g., 20180301) into a SAS date value, which is necessary for date calculations.
  • Last Day of Month: intnx('month', sas_date, 0, 'end') gives us the final calendar day of the month for each record's date.
  • Adjust to Last Weekday:
    • weekday() returns 1 for Sunday and 7 for Saturday.
    • If the last day is Sunday, subtract 2 days to get the preceding Friday.
    • If it's Saturday, subtract 1 day to get Friday.
    • For all other days (weekdays), we leave it as is.
  • Convert Back to Numeric Format: put(last_weekday, yymmddn8.) turns the SAS date back into a character string in YYYYMMDD format, then input(...,8.) converts it back to numeric to match your original Date variable type.

Notes:

  • If your dataset needs to account for company-specific holidays (not just weekends), you'd need a separate holiday dataset and use SAS's workday() function or a custom loop to exclude those dates. Feel free to ask for help with that if needed!
  • The format statement at the end is optional but makes the output easier to read when viewing the dataset.

Testing this code with your sample input will give you exactly the output you're looking for: each record gets the correct last weekday of its month as the Enddate variable.

内容的提问来源于stack exchange,提问作者Alan Ciao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:52:20