Search code examples
datesassas-macrodo-loops

SAS macro looping by date, how to indicate the correct step?


I need to create 3 SAS tables for years, quarters and months which would encompass a designated range from the today's date. I guess there is a smarter way to do it, but I ended up with something like (say, if I need to go 5 years back):

    %macro asd;

%let today = %sysfunc(today());
%let end_year = %sysfunc(intnx(year,&today,-5));


proc sql;
create table years
(
Years num informat = date9. format = date9.
);

insert into years

%do i = &today. %to &end_year. %by -365;
%if i = &today.-365 %then %do;
values(&i.-1)
%end;
%else %do;
values(&i.) 
%end;
%end;
;
quit;

%mend asd;
%asd;
run;

The problem is that I don't know how to indicate a step in the loop as a date period, so I ended up with exact numbers, which vary (for year - every 4 years, for month - every second month, for quarters - every 16 quarters).

I added a loop for a year to try and account at least for several leap years, but it doesn't work. So before proceeding to months and probably implementing another nested looping I wanted to ask if there is an easier way to create such tables?

Thanks! :)


Solution

  • Change your loop to loop over the number of years and calculate the macro variable needed inside the loop instead.

    Example - non macro version.

     Do I=1 to 5;
         Year=intnx('year', date, 1);
    
          Rest of code;
     End;