sassummultiple-entries

How to sum individual entries from multiple tables in SAS


What I have:

Team A

Material Accommodation Travel

Jan 8 12 10

Feb 8 15 30

Mar 9 12 20

Team B

Material Accommodation Travel

Jan 4 18 20

Feb 7 14 20

Mar 6 12 10

Team C

Material Accommodation Travel

Jan 5 18 10

Feb 9 15 30

Mar 9 12 10

What I want:

Sum

Material Accommodation Travel

Jan 17 48 40

Feb 24 44 80

Mar 24 36 40

I want to sum each entry across the three tables.

Code to reproduce tables:

proc sql;
   create table TeamA
       (Material num, Accommodation num, Travel num);

insert into TeamA
    values(8,12,10)
    values(8,15,30)
    values(9,12,20);
run;


proc sql;
   create table TeamB
       (Material num, Accommodation num, Travel num);

insert into TeamB
    values(4,18,20)
    values(7,14,20)
    values(6,12,10);
run;


proc sql;
   create table TeamC
       (Material num, Accommodation num, Travel num);

insert into TeamC
    values(5,18,10)
    values(9,15,30)
    values(9,12,10);
run;

Solution

  • Use SQL union all corresponding statement and sql aggregate function sum():

    proc sql;
       create table TeamA
           (month char(3), Material num, Accommodation num, Travel num);
    
    insert into TeamA
        values('Jan',8,12,10)
        values('Feb',8,15,30)
        values('Mar',9,12,20);
    run;
    
    
    proc sql;
       create table TeamB
           (month char(3), Material num, Accommodation num, Travel num);
    
    insert into TeamB
        values('Jan',4,18,20)
        values('Feb',7,14,20)
        values('Mar',6,12,10);
    run;
    
    
    proc sql;
       create table TeamC
           (month char(3), Material num, Accommodation num, Travel num);
    
    insert into TeamC
        values('Jan',5,18,10)
        values('Feb',9,15,30)
        values('Mar',9,12,10);
    run;
    
    proc sql noprint;
      create table allteam as 
      select month, 
        sum(material) as material,
        sum(accommodation) as accommodation,
        sum(travel) as travel
      from (
        select * from teama
        union all corresponding
        select * from teamb
        union all corresponding
        select * from teamc
      )
      group by month
      ;
    quit;