BookmarkSubscribeRSS Feed
dwsmith
Obsidian | Level 7

Consider the following SAS code:

data test;
format date date9.
ctry_cd $2.
sn $2.;
input ctry_cd sn date;
datalines;
US 1 20000
US 1 20001
US 1 20002
CA 1 20003
CA 1 20004
US 1 20005
US 1 20006
US 1 20007
ES 2 20001
ES 2 20002
;
run;

proc sql;
create table check as
select
sn,
ctry_cd,
min(date) as begin_dt,
max(date) as end_dt
from test
group by sn, ctry_cd;
quit;

This returns:

1 CA 07OCT2014 08OCT2014
1 US 04OCT2014 11OCT2014
2 ES 05OCT2014 06OCT2014

I would like for the `proc sql` distinguish between the country moves; that is, return

1 US 04OCT2014 06OCT2014
1 CA 07OCT2014 08OCT2014
1 US 09OCT2014 11OCT2014
2 ES 05OCT2014 06OCT2014

So it still groups the instances by sn and ctry_nm but pays attention to the date so I have a timeline.

 

2 REPLIES 2
Reeza
Super User

Proc means to the rescue!

The NOTSORTED option will allow it to process the data in the order it encounters it, so this does assume your data is in the order you want it. 

 

proc means data=test min max;
by sn ctry_cd notsorted;
var date;
ods output summary=want;
run;

proc print data=want;
format date: date9.;
run;

Another option would be to create a group identifier for each group within the dataset, using a data step and then apply a proc sql step. 

PGStats
Opal | Level 21

You need a data step or a data view to deal with sequential aspect of your processing. Here is how it can be done with a data view:

 

data test;
format date date9.
ctry_cd $2.
sn $2.;
input ctry_cd sn date;
datalines;
US 1 20000
US 1 20001
US 1 20002
CA 1 20003
CA 1 20004
US 1 20005
US 1 20006
US 1 20007
ES 2 20001
ES 2 20002
;

data testSeq / view=testSeq;
set test; by ctry_cd notsorted;
seq + first.ctry_cd;
run;

proc sql;
create table check as
select 
    sn, 
    ctry_cd,
    min(date) as begin_dt format=date9.,
    max(date) as end_dt format=date9.
from testSeq
group by seq, sn, ctry_cd;
drop view testSeq;
quit;
PG

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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