简体   繁体   English

如何在SAS Proc SQL中编写条件条件where语句?

[英]How to write conditional where statement in SAS Proc SQL?

I have a macro that would be used for multiple conditions. 我有一个可用于多种条件的宏。

%macro Average(data=, tablename=, element=, variablename=, time =);
   PROC SQL;
      CREATE TABLE &tablename. AS 
      SELECT ID, AVG(&element.) AS &variablename.
      FROM &data.
      WHERE date_time < &time or date_time > &time + 1 /*first where condition*/
      GROUP BY ID;
   QUIT;
%mend;

/*second where condition*/  WHERE &Lower. < date_time < &Upper.
/*third where condition*/   WHERE &BP > 0 and &SP<100

I want to put all these three where statements together into the sql macro instead of copy the macro three times. 我想将所有这三个where语句放到sql宏中,而不是复制宏三遍。 But how could I realize it? 但是我怎么能意识到呢?

If you want to optionally call different combinations of where conditions you could do something like the below where you set them to default to 1 unless you assign them to an additional where condition: 如果要有选择地调用where条件的不同组合,则可以执行以下操作,将它们设置为默认值为1除非将它们分配给其他where条件:

%macro Average(data=, tablename=, element=, variablename=, time=
              ,whr1=1
              ,whr2=1
              ,whr3=1);

  PROC SQL;
  CREATE TABLE &tablename. AS 
    SELECT ID, AVG(&element.) AS &variablename.
    FROM &data.
    WHERE (&whr1) and (&whr2) and (&whr3)
    GROUP BY ID;
 QUIT;
%mend;

Then you could call the macro with your where conditions eg: 然后,您可以使用where条件调用该宏,例如:

%Average(whr1=%str(date_time < &time or date_time > &time + 1))

%Average(whr1=%str(date_time < &time or date_time > &time + 1)
        ,whr2=%str(&Lower. < date_time < &Upper.)
        ,whr3=%str(WHERE &BP > 0 and &SP<100))

Simply use %if %then %else macro condition, with a new parameter here defined whr: 只需使用%if%then%else宏条件,并在此处定义一个新参数whr:

%macro Average(data=, tablename=, element=, variablename=, time =, whr=);
    PROC SQL;
    CREATE TABLE &tablename. AS 
    SELECT ID, AVG(&element.) AS &variablename.
    FROM &data.
    %if &whr=1 %then %do;
    WHERE date_time < &time or date_time > &time + 1 /*first where condition*/
    %end;
    %else %if &whr=2 %then %do;
    WHERE &Lower. < date_time < &Upper.
    %end;
    %else %if &whr=3 %then %do;
    WHERE &BP > 0 and &SP<100
    %end;
    %else %put 'NO WHERE SPECIFIED';
    GROUP BY ID;
    QUIT;
    %mend;

If the parameter declaration you specify whr=1, it will be the default value. 如果您指定参数声明whr = 1,它将是默认值。 Using %if %then %else you can also use different condition internal to the macro, I mean if you wanna use the first where statement if some condition is true you can specify them. 使用%if%then%else,您还可以在宏内部使用不同的条件,这意味着如果您想使用第一个where语句(如果某些条件为真),则可以指定它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM