SAS Select 进入动态命名
SAS Select Into Dynamic Naming
我正在尝试将 SAS proc sql select 用于 8 种不同的场景。
%MACRO Loop();
proc sql;
%do i=1 %to 8;
select total_value
into :Sol_&i. separated by ','
from Master.adjusted_hours
where Solicitation = "&i.";
%end;
quit;
%mend;
%Loop();
然而,当我使用 %put 函数时,无法识别宏变量。错误是“表观符号引用 SOL_1 未解析。”
%put &Sol_1;
如何将值存储在此宏变量中并稍后在代码中调用它?
需要声明SOL_1SOL_2等为全局宏变量。我不确定您的数据中包含什么,所以我创建了一些虚拟数据。
%global SOL_1 SOL_2 SOL_3 SOL_4 SOL_5 SOL_6 SOL_7 SOL_8;
data adjusted_hours;
do x = 1 to 8;
solicitation=put(x, 1.);
do total_value = 1 to 10;
output;
end;
end;
drop x;
run;
%MACRO Loop();
proc sql noprint;
%do i = 1 %to 8;
select total_value
into : Sol_&i. separated by ','
from adjusted_hours
where Solicitation = "&i.";
%end;
quit;
%mend;
%Loop();
%put _USER_;
Partial log:
GLOBAL SOL_1 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_2 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_3 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_4 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_5 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_6 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_7 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_8 1,2,3,4,5,6,7,8,9,10
如果您想完全避免使用宏并且必须声明 %global 变量,这里有一个数据步骤解决方案,只要您的数据集按 Solicitation 排序就可以使用。
data _null_;
set adjusted_hours;
by solicitation;
format temp .;
retain temp ;
temp=CATX(',',temp, total_value);
if last.solicitation then do;
call symputx(CATS('SOL_', solicitation), temp);
call missing(temp);
end;
run;
我正在尝试将 SAS proc sql select 用于 8 种不同的场景。
%MACRO Loop();
proc sql;
%do i=1 %to 8;
select total_value
into :Sol_&i. separated by ','
from Master.adjusted_hours
where Solicitation = "&i.";
%end;
quit;
%mend;
%Loop();
然而,当我使用 %put 函数时,无法识别宏变量。错误是“表观符号引用 SOL_1 未解析。”
%put &Sol_1;
如何将值存储在此宏变量中并稍后在代码中调用它?
需要声明SOL_1SOL_2等为全局宏变量。我不确定您的数据中包含什么,所以我创建了一些虚拟数据。
%global SOL_1 SOL_2 SOL_3 SOL_4 SOL_5 SOL_6 SOL_7 SOL_8;
data adjusted_hours;
do x = 1 to 8;
solicitation=put(x, 1.);
do total_value = 1 to 10;
output;
end;
end;
drop x;
run;
%MACRO Loop();
proc sql noprint;
%do i = 1 %to 8;
select total_value
into : Sol_&i. separated by ','
from adjusted_hours
where Solicitation = "&i.";
%end;
quit;
%mend;
%Loop();
%put _USER_;
Partial log:
GLOBAL SOL_1 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_2 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_3 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_4 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_5 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_6 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_7 1,2,3,4,5,6,7,8,9,10
GLOBAL SOL_8 1,2,3,4,5,6,7,8,9,10
如果您想完全避免使用宏并且必须声明 %global 变量,这里有一个数据步骤解决方案,只要您的数据集按 Solicitation 排序就可以使用。
data _null_;
set adjusted_hours;
by solicitation;
format temp .;
retain temp ;
temp=CATX(',',temp, total_value);
if last.solicitation then do;
call symputx(CATS('SOL_', solicitation), temp);
call missing(temp);
end;
run;