如果proc sql“group by”组没有没有观察,如何创建输出行

时间:2017-03-10 07:01:15

标签: sas proc-sql

我正在使用SAS Enterprise指南,并运行proc sql查询,如下所示:

proc sql; 
    CREATE TABLE average_apples AS
    SELECT farm, size, type, mean(apples) as average_apples
    FROM input_table
    GROUP BY farm, size, type
    ;
quit; 

对于我正在运行此查询的一些数据集,有些组没有分配给它们的观察,因此在查询输出中没有它们的条目。

如何强制此查询为每个组返回一行(例如0列中的值为apples

预先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我会这样做:

/* sample input table */
data input_table;
length farm size type $3 apples 8;
stop; /* try also with this statement commented out 
         to check the result for non-empty input table */
run;

proc sql; 
    CREATE TABLE average_apples AS
    SELECT farm, size, type, mean(apples) as average_apples
    FROM input_table
    GROUP BY farm, size, type
    ;
quit;

%let group_rows = &SQLOBS;
%put &group_rows;

data average_apples_blank;
if &group_rows ne 0 then set average_apples(obs=0);
else do;
   array zeros {*} _numeric_ /* or your list of variables */;
   do i=1 to dim(zeros);
      zeros[i] = 0;
   end;
   output; /* empty row */
end;
drop i;
run;


proc append base=average_apples data=average_apples_blank force;
run;

答案 1 :(得分:0)

试试这个

proc sql;
select f.farm, s.size, t.type, coalesce(mean(apples), 0) as average_apples
from (select distinct farm from input_table) as f
   , (select distinct size from input_table) as s
   , (select distinct type from input_table) as t
left join input_table as i
  on i.farm = f.farm and i.size = s.size and i.type t.type;
quit;

我没有测试它。它不起作用,把它放在评论中,我会调试它。