SAS 宏 - 有条件地打印结果

SAS Macro - Conditionally print results

我在 SAS 中有一个数据集,它有 22 个变量和 345 个观察值。变量包括 CliendID、class(坏或好)、持续时间、目的、saving_status 和。

我想写一个%client_type宏来显示以下所有信息(变量对应的观察):ClientID, Duration, purpose, Saving_status 如果客户信用良好。如果客户不是信用良好的客户(其 class 是 "bad"),它将显示消息 "Bad Customer".

宏 %client_status 应该接收 CliendID 作为参数 (ClientID)。

我使用了下面的代码,但它不起作用,而且当我调用宏 (%client_status(11254858)) 时没有任何输出。

%macro status_client(data,ClientID);
   proc sql;
   select class from project3.dada_credit where ClientID = &CliendID. as Credit;
   quit;

   %let class = Credit;

   %if &class. = "good" %then %do;
      proc print data = data_credit;
      var ClientID duration purpose saving_status;
      run;
   %end;

   %else %do;
      %put &ClientID. "Is a bad credit customer";
   %end;

%mend status_client;

我该如何修改?

我怀疑这就是你想要的。您的 SQL 是错误的,您应该始终首先从工作代码开始。

更正:

  1. 修改PROCSQL代码创建宏变量CLASS
  2. 删除不需要的 %LET
  3. 从宏变量比较中删除引号,因为这是文本。请注意,比较将区分大小写。
  4. 为查询添加一个过滤器以将结果限制为仅客户端,因为打印每个人的结果没有意义。
  5. 删除数据参数,因为它从未在宏中使用过。
  6. 你的宏调用不正确,status_client vs client_status

    %macro status_client(ClientID);
    proc sql NOPRINT;
        select class into : class from project3.dada_credit where ClientID=&CliendID.;
    quit;
    
    %if &class.=good %then
        %do;
    
            proc print data=data_credit;
                WHERE clientID=&clientID;
                var ClientID duration purpose saving_status;
            run;
    
        %end;
    %else
        %do;
            %put &ClientID. "Is a bad credit customer";
        %end;
    %mend status_client;
    
    %status_client(11254858);
    

使用当前宏的最大问题是调用它时没有为 CLIENTID 参数设置值。由于您在宏调用中使用了位置参数,因此您的调用正在设置 DATA 参数的值并将 CLIENTID 留空。

我想你想要做的是使用第一个 SQL 查询来设置一个宏变量,然后你可以在你的 %IF/%THEN/%ELSE 逻辑中测试它。要使用 SQL 设置宏变量,您需要使用 INTO 子句。如果您的 SQL 查询没有找到任何匹配的观察结果,您应该启动宏变量。

%macro status_client(ClientID,dsn=project3.data_credit);
%local credit ;
%let credit=NOTFOUND;
proc sql noprint;
select upcase(class)
  into :credit trimmed 
  from &dsn 
  where ClientID = &CliendID. 
;
quit;

%if (&credit. = GOOD ) %then %do;
proc print data = &dsn ;
  where ClientID = &CliendID. ;
  var ClientID duration purpose saving_status;
run;
%end;
%else %if (&credit = NOTFOUND) %then %put Client &clientid not found.;
%else %put Client &clientid has &credit credit.;
%mend status_client;