BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

Hello, 

 

I am trying to use a date variable to calculate the difference between two dates. I am trying to see the difference between the first and last observation for a given ID, but sometimes there are more than 2 observations per individual. Take the sample data below:

 

ID                DateStamp

1                 01AUG2020

1                 07SEP2020

2                 01AUG2020

2                 08AUG2020

2                 11SEP2020

3                 05JUN2020

3                 01AUG2020

 

I want to end up with a variable that is the date difference between the first ID entry and the last ID entry (for example, for ID #1, the date variable would be the difference between September 7 and August 1, for ID #2, the date variable would be the difference between August 1 and September 11, etc). 

 

Can someone help me with this? 

 

Thank you!

2 REPLIES 2
novinosrin
Tourmaline | Level 20
data have;
input ID                DateStamp :date9.;
format datestamp date9.;
cards;
1                 01AUG2020

1                 07SEP2020

2                 01AUG2020

2                 08AUG2020

2                 11SEP2020

3                 05JUN2020

3                 01AUG2020
;

proc sql;
 create table want as
 select id, range(datestamp) as datediff
 from have
 group by id;
quit;

/*Or*/

proc summary data=have nway;
 class id;
 var datestamp;
 output out=want range=Datediff;
 format datestamp;
run;
Cynthia_sas
SAS Super FREQ

Hi:

  And, in the interest of completeness.... if all you need is a report of the difference, you can get that directly from the original data (HAVE) without creating a second table using either PROC REPORT or PROC TABULATE:

Cynthia_sas_0-1600524494293.png

Using this code:


proc report data=have;
  title 'proc report solution';
  column id datestamp,range;
  define id / group;
  define datestamp/analysis ;
  define range / 'Difference' f=6.0;
run;

proc tabulate data=have f=6.0;
  title 'proc tabulate solution';
  class id;
  var datestamp;
  table id=' ',
        datestamp*range='Difference'/Box=ID;
run;
title;

Hope this helps,

Cynthia

 

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 380 views
  • 0 likes
  • 3 in conversation