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

Hi!
I am trying to make calculations with lagged values within proc sql (I know function lag is not working) as this is only subpart of a longer proc sql program.

Is it feasible?

data T;
input ID $ L M D ;
Datalines;
B 1 10 100 
B 1 20 100
C 1 30 200
C 2 40 200
D 1 50 300
D 2 60 300
D 3 70 300
;

proc sql;
Create table want as 
Select *, 
CASE 
WHEN L=1 THEN D-M
WHEN L=2 then  (SELECT D-LAG(M)  FROM T WHERE ID=A.ID AND L=a.L) 
else (SELECT M-Lag(D)  FROM T WHERE ID=A.ID AND L=a.L) 

END AS D1
FROM T AS A
;
QUIT

Output
B 1 10 100 90
B 1 20 100 80
C 1 30 200 170
C 2 40 200 170
D 1 50 300 250
D 2 60 300 250 
D 3 70 300 -230
1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26

The LAG function does not work in PROC SQL. Better you should do this in a DATA step.

--
Paige Miller

View solution in original post

3 REPLIES 3
PaigeMiller
Diamond | Level 26

The LAG function does not work in PROC SQL. Better you should do this in a DATA step.

--
Paige Miller
Jagadishkatam
Amethyst | Level 16

Please try below code

 

data T;
input ID $ L M D ;
Datalines;
B 1 10 100 
B 1 20 100
C 1 30 200
C 2 40 200
D 1 50 300
D 2 60 300
D 3 70 300
;

data want;
set t;
by id;
la=lag(m);
if first.id then la=.;
if l=1 then want=d-m;
else if l=2 then want=d-la;
else  want=m-d;

run;

Thanks,
Jag
cmemtsa
Quartz | Level 8

Thanks. It works with Data but I wanted to know whether is feasible with Proc Sql.

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
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
  • 3 replies
  • 507 views
  • 2 likes
  • 3 in conversation