为SAS中的条件创建宏。

huangapple go评论61阅读模式
英文:

Create macro for where condition in SAS

问题

我有一个包含150多个名称的数据集。示例 - A1、B1、C1、等等。

我有一段代码,用它来获取每个名称的销售额,目前我正在手动选择名称并运行以下查询。

create table want as 
select Name
,sum(sales) as sales
from have
where name in ('A1','B1')
group by Name
;quit;

我想以这样的方式运行此代码:每次从列表中选择一个名称,将结果存储在一个数据集中,然后选择另一个名称并存储在另一个数据集中,依此类推。最后将所有150个数据集追加到一个最终数据集中。请帮助我完成这个任务。谢谢。

英文:

I have a dataset which has more than 150+ names. Example - A1,B1,C1,…so on.

I have a code using which I'm getting sales for each name, right now I'm running the following query by selecting names manually.

create table want as 
select Name
,sum(sales) as sales
from have
where name in ('A1','B1')
group by Name
;quit;

I want to run this code in such a way that it picks one name from the list at a time and stores the results in a dataset then picks another name and stores in another dataset and so on. At the end appends all the 150+ datasets into one final dataset. Please help me do this. Thanks.

答案1

得分: 0

请注意,以下是您提供的代码的中文翻译:

假设您的名字存储在一个如下所示的单一数据集中:

名字
A1
B1
C1 
...

我会假设每个名字可能会有重复。我们将删除这些重复项,运行一个使用 call execute() 动态生成每个名字对应SQL的数据步骤,然后将每个数据集附加到最终的单一数据集末尾。

proc sort data=have(keep=name) out=names nodupkey;
    by name;
run;

data _null_;
    set names;

    call execute(cat(
     'proc sql;',
     '    create table tmp_', _N_, ' as',
     '        select name, sum(sales) as sales',
     '        from have',
     '        where name=', quote(name),
     '        group by name;',
     'quit;')
    );
run;

data want;
    set tmp_:;
run;
英文:

Let's assume your names are stored in a single dataset that looks as follows:

name
A1
B1
C1 
...

I'm going to assume that there could be duplicates of each one. We'll remove those duplicates, run a data step from call execute() to dynamically generate SQL for each name, then append each dataset to a single dataset at the end.

proc sort data=have(keep=name) out=names nodupkey;
    by name;
run;

data _null_;
    set names;

    call execute(cat(
     'proc sql;',
     '    create table tmp_', _N_, ' as',
     '        select name, sum(sales) as sales',
     '        from have',
     '        where name=', quote(name),
     '        group by name;',
     'quit;')
    );
run;

data want;
    set tmp_:;
run;

huangapple
  • 本文由 发表于 2023年6月9日 02:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定