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

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
Meteorite | Level 14

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
Meteorite | Level 14

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;

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
  • 324 views
  • 1 like
  • 3 in conversation