简体   繁体   English

SAS:总结proc sql

[英]SAS: Summing in proc sql

I am working on a SAS project where I am being asked to sum down on rows. 我正在做一个SAS项目,要求我对行进行总结。 Here's the code I have: 这是我的代码:

proc sql;
  create table total as
    select 
      sum(ans1) as sum1,
      sum(ans2) as sum2,
      sum(ans3) as sum3,
      sum(ans4) as sum4
    from proj.scores;
quit;

My problem is there are 150 variables (labeled ans1-ans150). 我的问题是有150个变量(标记为ans1-ans150)。 Is there a way to sum each of them without having to continue what I have all the way to 150? 有没有一种方法可以对每个变量进行求和,而不必继续我一直达到的150?

I think the proper tool would make the whole process much easier. 我认为适当的工具将使整个过程更加容易。 SQL does not have features for working with large lists of variables. SQL没有用于处理大量变量的功能。

proc summary;
   output out=sum sum(ans1-ans150)=sum1-sum150;
   run;

Yes, you can do this using macro logic and replacing your 1, 2, 3... rows with a loop. 是的,您可以使用宏逻辑并用循环替换您的1、2、3 ...行来执行此操作。 This method uses a "backstop" variable so that the comma in your loop does not cause an error on the 150th iteration of the loop (this variable is dropped). 此方法使用“ backstop”变量,以便循环中的逗号不会在循环的第150次迭代中引起错误(删除此变量)。

%macro summer;

    proc sql;
        create table total (drop = backstop) as select
            %do i = 1 %to 150;
                sum(ans&i.) as sum&i.,
            %end;
            "" as backstop
            from proj.scores;
    quit;

%mend summer;

%summer;

A better approach (in my opinion), is to use the macro this way: 更好的方法(我认为)是通过以下方式使用宏:

data have;
input x1-x10;
datalines;
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
;;;;
run;

%macro sum_loop(prefix=, outfix=, start=1, end=);
%local i;
%do i = &start. %to &end.;  /* loop over start to end */
  sum(&prefix.&i.) as &outfix.&i.   /* the actual SQL statement */
  %if &i < &end %then %do; , %end;  /* that way you get commas after all non-last entries */
%end;
%mend sum_loop;

proc sql;
  create table total as
    select 
      %sum_loop(prefix=x,outfix=sum,start=1,end=10)
    from have
  ;
quit;

That way, the macro is just responsible for what you need looped. 这样,宏只负责您需要循环的内容。 That makes it more reusable and easier to maintain - WHERE and FROM and such are separate.. Even better would be to split out the inner portion as its own macro, and have a generic looper macro, but here that might be overkill... 这使得它更可重用且更易于维护-WHERE和FROM等是分开的。更好的办法是将内部拆分为自己的宏,并具有通用的looper宏,但在这里可能会过大...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM