【问题标题】:How to create an output row if a proc sql “group by” group has no no observations如果proc sql“group by”组没有观察结果,如何创建输出行
【发布时间】:2017-03-10 19:58:33
【问题描述】:

我在 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; 

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

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

感谢您的帮助!

【问题讨论】:

  • 如果您提供一些示例源数据,将更容易回答。看起来您有一个数据集,将水果(例如苹果)的值存储在单独的列中,而不是有一个标识水果的列和一个单独的值列(这是一个更正常的结构)。您是说对于某些数据集,查询中引用的列不存在?
  • 您是否有一个数据集,其中包含您希望在输出中包含的所有组(即农场大小类型的所有组合)?如果是这样,您可以将其加入到您的输出表中。

标签: sas proc-sql


【解决方案1】:

我会这样做:

/* 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;

【讨论】:

    【解决方案2】:

    试试这个

    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;
    

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

    【讨论】:

    • 嗨,德克。当我运行它时,我收到以下错误:ERROR: correlated reference to column farm is not contained within the subquery.
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多