使用" for循环"在SAS SQL?

时间:2018-05-17 20:12:47

标签: sql sas

我在SAS中使用SQL。我的数据中有很多类似的变量名,例如" var1,var2,...,var100"。我知道它可以写成

proc sql; select xx from xxx where var1 = a or var2 =a or var3 =a;run; 

我想知道SQL是否具有类似" for loop"的函数。使这项任务更容易?

感谢您的帮助!

6 个答案:

答案 0 :(得分:2)

正如汤姆所说,在数据步骤中这将更加容易:

data want;
   set xxx;
where whichc('a', of var1-var1000);
run;

答案 1 :(得分:0)

根据数据库变体,您可以执行此操作:

... WHERE a IN (var1, var2, var3, etc);

但这将是您能做的最好的事情,我不知道SAS是否支持它。

答案 2 :(得分:0)

据我所知,在SAS的每个交互中都有一个select co.Data as phone, co2.Data as Email from Users u left join Contacts co on c.id=u.id left join Contacts co2 on c2.id=u.id where co.Name='email' and co2.Name='phone' --if i dont add this emails and ebverything show up 循环功能。

IIRC,我认为它有点像:

Do

答案 3 :(得分:0)

您可以使用宏来完成工作。 例如:

%macro loopQuery;

  proc sql; 
    select xx 
    from xxx 
    where var1 = a 
     %do i=2 %to 100;
       or var&i.=a
     %end;
    ;
  run; 
%mend;

%loopQuery;

答案 4 :(得分:0)

您可以使用WHICH()WHICHC()功能进行此类测试。它将返回匹配的第一个变量的索引,如果没有匹配则返回零。 SAS会将​​0视为错误。

where which(a,var1,var2,var3)

不幸的是,如果使用PROC SQL,则必须列出每个变量名称。与DATA步骤不同,它不支持变量列表。

答案 5 :(得分:0)

你可以使用macrovariable然后使用它。但这是一个漫长而乏味的过程,而datastep则要简单得多。您可以在proc sql中执行此操作,如下所示。

/*first create dataset to test*/
data have;
  input var1 var2 var3 var4 newvar  a;
  datalines;
 10 20 30 40 60 10
10 20 30 40 60 90
10 20 30 40 60 20
;
run;

 /* create macro variable*/
 proc sql;
   select catt(name, "  =  ", " a  or ") into :VAR SEPARATED by " "  
 from  dictionary.columns 
 where memname = 'HAVE'
 and prxmatch("m/^VAR\d+$/i", trim(name)) > 0;/* to find variable var with  digit*/

%put &VAR;

它给出var1 = a或var2 = a或var3 = a或var4 = a或

/* do a substring to remove last or */
%let final_var = %substr(&var, 1, %length(&var)-2);

%put &final_var;

它给出var1 = a或var2 = a或var3 = a或var4 = a

 /*Now you can use the macro variable in your query, will give you desired 
result*/

proc sql;
select * from have
where &final_var;