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-white.png

Special offer for SAS Communities members

Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.

 

View the full agenda.

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