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 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 587 views
  • 4 likes
  • 5 in conversation