2015-05-28 117 views
2

我有一個將用於多個條件的宏。如何在SAS Proc SQL中編寫條件where語句?

%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 

我想把所有這三個語句放在一起放入sql宏而不是複製宏三次。但我怎麼能意識到這一點?

回答

0

如果%,那麼其他%宏條件只需使用%,以新的參數這裏定義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%否則你也可以在宏內部使用不同的條件,我的意思是如果你想使用第一個where語句,如果某些條件爲真,你可以指定它們。

+1

這可行,但我發現這比讀取WHERE條件更難以閱讀,而且難以維護。 – Joe

3

如果你想有選擇地撥打你可以做下面,你將它們有點像默認爲1where條件的不同組合,除非你將它們分配給額外的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)) 
+0

我更喜歡這種方式 - 使where條件本身成爲宏觀參數。更靈活,更易於閱讀/理解代碼。 – Joe