Help using Base SAS procedures

How to sum observation according to multiple conditions

Accepted Solution Solved
Reply
Contributor
Posts: 50
Accepted Solution

How to sum observation according to multiple conditions

Hello,

 

I have a table such as

ID           Sales     Year     Sales_classification

1             12         2008              4567

1              11        2008               7890

1              13        2008               5678

1              14        2009               4567

1              15        2009               7890

1               16       2009               5678

2                8       2008               4567

2              1        2008               7890

2              3        2008               5678

2              4        2009               4567

2              5        2009               7890

2               6       2009               5678

 

Condition includes:

IF

With the same ID

With the same YEAR

Sales_classification first digit larger than 6

 

THEN

sum the SALES meet all the conditions above

 

This may be done with or without CONDITION proc, there may be several ways and logic to do this.

Would you please help me with it?

 

Thank you very much!

 

 


Accepted Solutions
Solution
‎02-01-2018 02:45 PM
Esteemed Advisor
Posts: 5,523

Re: How to sum observation according to multiple conditions

Then switch to:

 

proc sql;
create table want as
select 
    ID, 
    year, 
    sum(case when first(cats(Sales_classification)) > "6" 
        then Sales 
        else 0 end) as sumSales
from have
group by id, year;
quit;
PG

View solution in original post


All Replies
Esteemed Advisor
Posts: 5,523

Re: How to sum observation according to multiple conditions

You could do:

 

proc sql;
create table want as
select ID, year, sum(Sales) as sumSales
from have
where first(cats(Sales_classification)) > "6"
group by id, year;
quit;
PG
Contributor
Posts: 50

Re: How to sum observation according to multiple conditions

OMG

You are awesome! It exactly does what I want. It is so neat and clean.

 

But the outcome table only shows the observation meet the condition. What if I also want those obs show "0" if do not meet the condition?

Solution
‎02-01-2018 02:45 PM
Esteemed Advisor
Posts: 5,523

Re: How to sum observation according to multiple conditions

Then switch to:

 

proc sql;
create table want as
select 
    ID, 
    year, 
    sum(case when first(cats(Sales_classification)) > "6" 
        then Sales 
        else 0 end) as sumSales
from have
group by id, year;
quit;
PG
Contributor
Posts: 50

Re: How to sum observation according to multiple conditions

Great!

 

Thank you!

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 176 views
  • 1 like
  • 2 in conversation