miércoles, 15 de agosto de 2012

SAS Dates - Macro Style!

When working with processes in SAS that depend on dates, it is pretty useful to define all the standard dates we are most likely to use, so we don't have to go through the mess of coding them all again in every process. This will make our code cleaner and easier to understand, by using macro variables like "current_month" or "first_day_of_month" instead of complex date expressions.
One way to do this is by defining macro variables that store the date values we need. In te following example, I will show you how to define various useful dates with the YYYYMMDD format (that is year/month/day as in 20120821 ):
 
/* Example 1: Defining relevant days*/

/* Get the current date, let's assume today is 21 August 2012*/
%let today_date        = %sysfunc(today());

/* Define the current day and previous day (ie. 20120621 and 20120620) */
%let current_day       = %sysfunc(putn(&today_date, yymmddn.));
%let previous_day     = %sysfunc(putn(%sysfunc(intnx(DAY,&TODAY.,-1)), yymmddn.));

/* Define the first and last day of the month (ie: 20120601 and 20120630) */
%let first_day_month = %sysfunc(putn(%sysfunc(intnx(MONTH,&TODAY.,0,B)), yymmddn.));
%let last_day_month = %sysfunc(putn(%sysfunc(intnx(MONTH,&TODAY.,0,E)), yymmddn.));
And of course we can define dates in any other format we wish, like relevant months:
/* Example 2: Defining relevant months*/

/* Define current month, 6 months ago and 12 months ago (ie: 201206, 201112 and 201106) */
%let month_current   = %sysfunc(putn(&today, yymmn.)); 
%let month_6           = %sysfunc(putn(%sysfunc(intnx(MONTH,&TODAY.,-6)), yymmn.));
%let month_12          = %sysfunc(putn(%sysfunc(intnx(MONTH,&TODAY.,-12)), yymmn.)); 
 

So, if we have process that has to extract, let's say, the number of users during the last six months from a table where we have a field "date_registered" defined as YYYYMMDD. We could easily write the solution as:
/* Example 3: How to use our fancy macros*/

proc sql;
  select count(*) from clients where date_registered >= &month_6.;
quit;

  

No hay comentarios:

Publicar un comentario