BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Emma2021
Quartz | Level 8

I would like to calculate difference within ID. I have a below SAS code, how can I change this to SQL?

data tmp1;

set tmp;

by ID;

dif_day=dif(day);

if first.id then dif_day=.;

run;

 

 

data have;
input id day ;
cards;
1 1
1 1
2 4
2 4
2 5
3 3
3 3
3 3
3 4
3 4
;
data want;
set have;
by id;
dif_day=dif(day);
if first.id then dif_day=.;
run;

 

Thank you.

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User

It is not easy for SQL , you need a index variable to identity a unique row.

 

data have;
input id day ;
n+1;
cards;
1 1
1 1
2 4
2 4
2 5
3 3
3 3
3 3
3 4
3 4
;

proc sql;
create table want as
select id,day,day-(select day from have where id=a.id and n=a.n-1) as dif
 from have as a;
quit;

View solution in original post

4 REPLIES 4
ballardw
Super User

There is basically no guarantee that SQL will process records in any given order so the concept of DIF (and closely related LAG) functions is basically a non-starter. I won't say it can't be done but there can be considerably more work needed. Use a data step as that is the correct tool if you need to process data in a given order.

 

Also SQL will not have anything related to the FIRST. or LAST. functionality.

 


@Emma2021 wrote:

I would like to calculate difference within ID. I have a below SAS code, how can I change this to SQL?

data tmp1;

set tmp;

by ID;

dif_day=dif(day);

if first.id then dif_day=.;

run;

 

Thank you.


 

Kurt_Bremser
Super User

If you give us example data in usable form, we might be able to give you an example of SQL code, but it won't look good, and the performance may well be horrible.

Reeza
Super User
You may want to consider learning PL/SQL if you have Oracle and want similar functionality in SQL.

To do this type of calculation you would need different logic but if you had SAS dates it would be easier.

Ksharp
Super User

It is not easy for SQL , you need a index variable to identity a unique row.

 

data have;
input id day ;
n+1;
cards;
1 1
1 1
2 4
2 4
2 5
3 3
3 3
3 3
3 4
3 4
;

proc sql;
create table want as
select id,day,day-(select day from have where id=a.id and n=a.n-1) as dif
 from have as a;
quit;

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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
  • 4 replies
  • 373 views
  • 4 likes
  • 5 in conversation