Hi I'm having trouble getting the answer to a very trivial problem.
I'm trying to get my previous date (year and month) to account for the flip of the year scenario.
Example:
yyyymm = 201805
pyyyymm = 201804
yyyymm = 201801
pyyyymm = 201712
But the following program just spews out 201800 for when yyyymm = 201801...and i cant figure out why?
Thanks.
%let yyyymm = 201801;
%let yr = %sysfunc(substr(&yyyymm,1,4));
%let mth = %sysfunc(substr(&yyyymm,5,2));
data null_;
if "&mth" = '01' then do;
%let pyyyymm = cats(&yr.-1, 12);
end;
else do;
%let pyyyymm = &yyyymm.-1;
end;
run;
Are you looking to do something like this?
%macro waldo11;
%let yyyymm = 201801;
%let yr = %sysfunc(substr(&yyyymm,1,4));
%let mth = %sysfunc(substr(&yyyymm,5,2));
%if &mth = 01 %then %do;
%let pyyyymm = %sysfunc(cats(&yr.-1, 12));
%end;
%else %do;
%let pyyyymm = %val(&yyyymm.-1);
%end;
%put pyyyymm=&pyyyymm;
%mend waldo11;
%waldo11
/*or*/
%let yyyymm = 201801;
%let yr = %sysfunc(substr(&yyyymm,1,4));
%let mth = %sysfunc(substr(&yyyymm,5,2));
data _null_;
if "&mth" = '01' then do;
call symput( 'pyyyymm',cats(&yr.-1, 12));
end;
else do;
call symput('pyyyymm',&yyyymm.-1);
end;
run;
%put &=pyyyymm;
Macro code is used to generate SAS code. By the time the SAS code starts running the macro code has been run already.
So you are running these commands.
%let yyyymm = 201801;
%let yr = %sysfunc(substr(&yyyymm,1,4));
%let mth = %sysfunc(substr(&yyyymm,5,2));
%let pyyyymm = cats(&yr.-1, 12);
%let pyyyymm = &yyyymm.-1;
data null_;
if "&mth" = '01' then do; end;
else do; end;
run;
If you want to use your data step to generate macro variables then use the CALL SYMPUTX() function.
data null_;
if "&mth" = '01' then call symputx('pyyyymm',cats(&yr.-1, 12));
else call symputx('pyyyymm',&yyyymm.-1);
run;
Of course if you are just trying to subtract one month from a date then convert your strings into dates and use functions.
%let pyyyymm=%sysfunc(intnx(month,%sysfunc(inputn(&yyyymm.01,yymmdd8)),-1),yymmn6);
Definitely, as @Tom said, you should be using SAS dates to do the calculations and the INTNX function to do this.
Don't try to do math on human readable dates.
If you need to convert the results to a human readable format (which SAS dates are not), then when you do the output, apply the proper format.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.