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

编写SAS宏实现WHERE条件单名称循环处理并合并数据集

SAS宏实现按名称单独汇总并合并数据集

步骤1:提取所有唯一名称

先从原数据集have中提取不重复的Name值,存到临时数据集,避免手动枚举150+个名称:

proc sql noprint;
    create table names_list as
    select distinct Name
    from have;
quit;

步骤2:批量生成单个名称的汇总数据集

用宏循环遍历所有唯一名称,为每个名称单独生成汇总数据集,表名格式为want_&名称:

%macro generate_single_ds;
    /* 获取名称总数,确定循环次数 */
    proc sql noprint;
        select count(*) into :total_names from names_list;
    quit;

    /* 逐个处理每个名称 */
    %do i=1 %to &total_names;
        /* 取出当前循环对应的名称 */
        data _null_;
            set names_list(obs=&i firstobs=&i);
            call symputx('current_name', Name, 'G');
        run;

        /* 生成单个名称的汇总表 */
        proc sql;
            create table want_&current_name as
            select Name, sum(sales) as sales
            from have
            where Name = "&current_name"
            group by Name;
        quit;
    %end;
%mend generate_single_ds;

/* 执行宏 */
%generate_single_ds;

步骤3:合并所有单个数据集

自动收集所有生成的want_*数据集,合并成最终的汇总表:

%macro combine_ds;
    /* 查询WORK库中所有以want_开头的数据集 */
    proc sql noprint;
        select memname into :ds_list separated by ' '
        from dictionary.tables
        where libname = 'WORK' and memname like 'WANT_%';
    quit;

    /* 合并所有数据集 */
    data final_want;
        set &ds_list;
    run;
%mend combine_ds;

/* 执行宏 */
%combine_ds;

可选简化写法(用call execute替代宏循环)

如果觉得宏循环麻烦,也可以用call execute直接生成所有执行语句,代码更简洁:

proc sql noprint;
    select cats('proc sql; create table want_', Name, ' as select Name, sum(sales) as sales from have where Name = "', Name, '" group by Name; quit;')
    into :execute_list separated by ' '
    from names_list;
quit;

/* 执行生成的所有语句 */
&execute_list;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:00:13