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

How to write conditional where statement in SAS Proc SQL?

我有一个可用于多个条件的宏。

%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

我想将这三个where 语句一起放入sql 宏中,而不是将宏复制三次。但是我怎么能意识到呢?

如果你想有选择地调用 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;

然后您可以使用 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))

简单地使用 %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;

如果您指定的参数声明whr=1,它将是默认值。 使用 %if %then %else 您还可以在宏内部使用不同的条件,我的意思是如果您想在某些条件为真时使用第一个 where 语句,您可以指定它们。