You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化包含两个GROUP BY语句的PROC SQL代码?

更紧凑的实现方案

优先推荐:SQL窗口函数实现

这是最简洁的单SQL语句写法,利用窗口函数直接在一次分组统计中同时得到细分计数与品牌总计数,无需多次分组或表关联:

proc sql noprint;
  create table tab3 as
  select 
    make,
    type,
    count(1) as count,
    sum(count(1)) over(partition by make) as total
  from sashelp.cars
  where origin='Asia'
  group by make, type
  order by make, type;
quit;

逻辑说明

  • 先按make, type分组,统计每个品牌下不同车型的细分数量count;
  • 通过sum(count(1)) over(partition by make)窗口函数,对同一make分组内的所有count求和,直接得到该品牌的总数量total;
  • 仅需一次扫描数据集即可完成所有计算,效率优于多次分组或关联写法。

其他可选方案

1. PROC SUMMARY 过程步实现

SAS的PROC SUMMARY专为多维度汇总设计,代码简洁高效:

proc summary data=sashelp.cars nway missing;
  where origin='Asia';
  class make type;
  output out=tab3_temp(drop=_type_ _freq_) n=count;
run;

data tab3;
  set tab3_temp;
  by make;
  retain total;
  if first.make then total = 0;
  total + count;
  output;
run;

2. 数据步实现(适合复杂自定义逻辑场景)

通过BY组处理与变量保留,实现分组统计:

proc sort data=sashelp.cars(where=(origin='Asia')) out=cars_sorted;
  by make type;
run;

data tab3;
  set cars_sorted;
  by make type;
  retain count total;
  if first.type then count = 0;
  count + 1;
  if first.make then total = 0;
  total + 1;
  if last.type then output;
run;

内容的提问来源于stack exchange,提问作者whymath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:22:26