[英]How to sum two columns based on another column condition in SAS and store the result in a variable
我有这样的数据:
ColumnA ColumnB ColumnC
1 10 20
1 10 30
0 50 10
0 50 20
1 10 40
我想对ColumnB和ColumnC的值求和,其中ColumnA = 1的值,并将结果存储在变量中,即,我想要120(ColumnB和ColumnC的总值,其中ColumnA = 1的值)并将此结果存储在变量中SAS。
与此同时,我也想在另一个变量中(在SAS中另一个变量中为130)(ColumnB和ColumnC的值之和,其中ColumnA = 0)
我试图在proc打印,均值等中创建一个变量。 甚至想到要在proc sql中执行此操作,但无法达到结果。
使用基本SQL轻松完成:
data have;
infile datalines;
input columnA columnB columnC;
datalines;
1 10 20
1 10 30
0 50 10
0 50 20
1 10 40
;
run;
proc sql;
select sum(ColumnB)+sum(ColumnC)
into: want
from have
where columnA=1
;
quit;
/* the result is stored in variable &want */
%put &want.;
编辑:回答您的后续问题,这将为您提供两个总和的两个输出变量:
data have;
infile datalines;
input columnA columnB columnC;
datalines;
1 10 20
1 10 30
0 50 10
0 50 20
1 10 40
;
run;
proc sql;
select sum(case when columnA=1 then ColumnB+ColumnC end) as A0
,sum(case when columnA=0 then ColumnB+ColumnC end) as A1
into: want0, :want1
from have
;
quit;
/* variable &want1 contains the result where ColumnA=1 and &want2 where ColumnA=0 */
%put &want0;
%put &want1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.