So I have a data named table1 as follows:
Obs ID M_201812 M_201901 M_201902 M_201903
1 X1 1 . . .
2 X2 1 1 . .
3 X3 . 1 1 .
4 X4 . 1 . .
5 X5 . 1 . .
6 X6 1 . . .
7 X7 1 1 . .
8 X8 1 1 . .
9 X9 . . 1 .
10 X10 1 1 . .
Each column here is a month, which is dynamically generated based on some previously run macro. The months will be dynamic and will vary. What I need to do is calculate sums of last 3 months, last 6 months and last 12 months. The approach I had in my mind was as follows: A) Store the column names in a macro variable:
proc sql noprint;
select distinct name
into :cols2 separated by ','
from dictionary.columns
where upcase(memname) = 'Table1' and name not in ('ID');
;
quit;
%put &cols2.
The output was as follows:
M_201812,M_201901,M_201902,M_201903
B) Create sums thereafter based on the number of items in the variable:
data table1;
set table1;
if count("&cols2",",") <=3 then do;
3m_total=sum(of &cols2);
6m_total=sum(of &cols2);
12m_total=sum(of &cols2);
end;
else if 3< count("&cols2",",") <=6 then do;
3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
6m_total=sum(of &cols2);
12m_total=sum(of &cols2);
end;
else if 6< count("&cols2",",") <=12 then do;
3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
6m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)));
12m_total=sum(of &cols2);
else do;
3m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)));
6m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)));
12m_total=sum(%scan(%superQ(cols2),-1,%str(,)),%scan(%superQ(cols2),-2,%str(,)),%scan(%superQ(cols2),-3,%str(,)),%scan(%superQ(cols2),-4,%str(,)),%scan(%superQ(cols2),-5,%str(,)),%scan(%superQ(cols2),-6,%str(,)),
%scan(%superQ(cols2),-7,%str(,)),%scan(%superQ(cols2),-8,%str(,)),%scan(%superQ(cols2),-9,%str(,)),%scan(%superQ(cols2),-10,%str(,)),%scan(%superQ(cols2),-11,%str(,)),%scan(%superQ(cols2),-12,%str(,)));
end;
run;
Basically we get 12 months sum only if there are 12 monthly columns available. If only 3 months are available, then 3months sum=6months sum=12months sum. After running the code, I get the following error:
ERROR 159-185: Null parameters for SUM are invalid.
This happens at the last else do statement. I can't for the life of me figure out why won't sas be able to read a simple if-then-do-else statement. Is there an error in the if conditions or in calling the macro variable? Any help here would be appreciated. Thanks a lot.
proc transpose
. – Parfait