Comparing dates in SAS is crucial for data analysis and manipulation. This tutorial demonstrates how to compare date variables with date constants using the WHERE=
option in a DATA
step. We’ll use an example to illustrate how to filter a dataset based on a specific date criteria.
Comparing Dates with Constants in the WHERE= Option
The WHERE=
option in the DATA
step allows you to filter observations based on specific conditions. To compare a date variable with a date constant, use the following syntax within the WHERE=
option:
WHERE=(date_variable < 'date_constant'd);
date_variable
: The name of the variable containing the dates you want to compare. This variable should be formatted as a SAS date.date_constant
: A SAS date constant in the format'ddMONyyyy'd
. For example,'01JAN1960'd
represents January 1st, 1960. The'd'
following the closing quote is essential and indicates a date constant. This format is consistent regardless of how your date variables are formatted or informatted.
Example: Filtering a Dataset by Birth Date
Let’s examine a practical example using a dataset named diet
. We want to create a new dataset containing only individuals born before January 1st, 1960.
DATA diet (where = (b_date < '01jan1960'd));
input subj 1-4 l_name $ 18-23 weight 30-32 +1 wt_date mmddyy8. @43 b_date mmddyy8.;
format wt_date b_date date9.;
DATALINES;
1024 Alice Smith 1 65 125 12/1/05 01/01/60
1167 Maryann White 1 68 140 12/01/05 01/01/59
1168 Thomas Jones 2 190 12/2/05 06/15/60
1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60
1302 Felicia Ho 1 63 115 1/1/06 06/15/58
;
RUN;
PROC PRINT data=diet;
title 'Birthdays in the diet data set before 01/01/1960';
RUN;
This code snippet filters the diet
dataset and outputs only records where the b_date
(birth date) is before January 1, 1960. Notice the use of the date9.
format, which displays dates in ddMonyyyy
format. Using four-digit years is generally recommended for clarity.
Understanding SAS Date Constants and Formats
SAS date constants always follow the 'ddMONyyyy'd
format. The date9.
format used in the example displays the date in a readable ddMonyyyy
format. Other formats like date7.
display the date as ddMonyy
.
Conclusion
Comparing dates in SAS using the WHERE=
option and date constants allows for efficient data filtering. Remember the specific format for SAS date constants ('ddMONyyyy'd
) and choose appropriate date formats for display based on your needs. This technique is fundamental for many data analysis tasks in SAS.