BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Ronein
Onyx | Level 15

Hello

I want to calculate sum of fields .

One of the fields in the sum is calculated variable.

Is there a way to calculate it in one step with SUM function?

This way is not working 

SUM(case when X<0 then abs(X) else 0 end as calc_X,Y,Z) as Total_Other_Way

 

 

Data have;
Input Cust_ID X Y Z;
cards;
1 -100 50 60
2 200 60 40
3 -300 30 20
4 400 10 90
5 250 80 20
;
Run;

proc sql;
create table want as
select *, 
       case when X<0 then abs(X) else 0 end as calc_X,
	   SUM(calculated calc_X,Y,Z) as Total,
	   SUM(case when X<0 then abs(X) else 0 end as calc_X,Y,Z) as Total_Other_Way
from have
;
quit;
1 ACCEPTED SOLUTION
4 REPLIES 4
Ksharp
Super User

I got no problem.

Data have;
Input Cust_ID X Y Z;
cards;
1 -100 50 60
2 200 60 40
3 -300 30 20
4 400 10 90
5 250 80 20
;
Run;

proc sql;
create table want as
select *, 
       case when X<0 then abs(X) else 0 end as calc_X,
	   SUM(calculated calc_X,Y,Z) as Total
from have
;
quit;

Or you could try this one:

Data have;
Input Cust_ID X Y Z;
cards;
1 -100 50 60
2 200 60 40
3 -300 30 20
4 400 10 90
5 250 80 20
;
Run;

proc sql;
create table want as
select *, 
       -X*(X<0) as calc_X,
	   SUM(calculated calc_X,Y,Z) as Total
from have
;
quit;
Ronein
Onyx | Level 15

Thank you but the solution provided is in two steps of calculation-

First you calculate the field X_calc 

Then you calculate TOTAL

My question is if can do it in one step  so the calculation of field X_Calc be inside the SUM function??

Ronein
Onyx | Level 15

Great,

Here is the solution as you offered


Data have;
Input Cust_ID X Y Z;
cards;
1 -100 50 60
2 200 60 40
3 -300 30 20
4 400 10 90
5 250 80 20
;
Run;

proc sql;
create table want as
select *, 
	   SUM(case when X<0 then abs(X) else 0 end,Y,Z) as Total_Other_Way
from have
;
quit;

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

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.

SAS Training: Just a Click Away

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

Browse our catalog!

Discussion stats
  • 4 replies
  • 1224 views
  • 1 like
  • 3 in conversation