2013-02-22 113 views
1

我正在尋找一個優雅的解決方案來解決下面的問題,這將有助於避免代碼重複。你可以看到,這條線:SAS - 哈希表和has_next

put auction_id= potential_buyer= ;* THIS GETS REPEATED; 

重複這段代碼獲得:

data results; 

    attrib potential_buyer length=$1; 

    set auction; 

    if _n_ eq 1 then do; 
    declare hash ht1(dataset:'buyers', multidata: 'y'); 
    ht1.definekey('auction_id'); 
    ht1.definedata('potential_buyer'); 
    ht1.definedone(); 
    call missing (potential_buyer); 
    end; 


    ** 
    ** LOOP THROUGH EACH POTENTIAL BUYER AND PROCESS THEM 
    *; 
    if ht1.find() eq 0 then do; 

    put auction_id= potential_buyer= ;* THIS GETS REPEATED; 

    ht1.has_next(result: ht1_has_more); 
    do while(ht1_has_more); 
     rc = ht1.find_next(); 

     put auction_id= potential_buyer= ;* THIS GETS REPEATED; 

     ht1.has_next(result: ht1_has_more); 
    end; 
    end; 
run; 

我已經簡化爲一條直線上面的例子作爲真正的代碼塊是相當漫長和複雜。如果可能的話,我想避免使用%macro片段或%include,因爲我想將邏輯保留在數據步驟「內」。

下面是一些樣本數據:

data auction; 
     input auction_id; 
    datalines; 
    111 
    222 
    333 
    ; 
    run; 

    data buyers; 
     input auction_id potential_buyer $; 
    datalines; 
    111 a 
    111 c 
    222 a 
    222 b 
    222 c 
    333 d 
    ; 
    run; 

回答

3

我想通了。原來是在年底非常簡單只是有一點點麻煩包裹我的大腦周圍:

data results; 

    attrib potential_buyer length=$1; 

    set auction; 

    if _n_ eq 1 then do; 
    declare hash ht1(dataset:'buyers', multidata: 'y'); 
    ht1.definekey('auction_id'); 
    ht1.definedata('potential_buyer'); 
    ht1.definedone(); 
    call missing (potential_buyer); 
    end; 


    ** 
    ** LOOP THROUGH EACH POTENTIAL BUYER AND PROCESS THEM 
    *; 
    if ht1.find() eq 0 then do; 

    keep_processing = 1; 
    do while(keep_processing); 

     put auction_id= potential_buyer= ;* THIS GETS DOESNT GET REPEATED ANYMORE =); 

     ht1.has_next(result: keep_processing); 
     rc = ht1.find_next(); 
    end; 
    end; 

run; 
1

你能解決這樣的....但羅布的回答是好。

data results; 

%Macro NoDuplicate; 
    Put auction_id= potential_buyer= ; * No Longer Duplicated; 
%Mend noduplicate; 

attrib potential_buyer length=$1; 

set auction; 

if _n_ eq 1 then do; 
    declare hash ht1(dataset:'buyers', multidata: 'y'); 
    ht1.definekey('auction_id'); 
    ht1.definedata('potential_buyer'); 
    ht1.definedone(); 
    call missing (potential_buyer); 
end; 

** 
** LOOP THROUGH EACH POTENTIAL BUYER AND PROCESS THEM 
*; 
if ht1.find() eq 0 then do; 

    %NoDuplicate 

    ht1.has_next(result: ht1_has_more); 
    do while(ht1_has_more); 
    rc = ht1.find_next(); 
    %NoDuplicate 
    ht1.has_next(result: ht1_has_more); 
    end; 
end; 

run; 
+0

同意,有什麼本質上錯的解決方案 - 我只是想保持良好格式化代碼的IDE(而而不是格式丟失的宏)。正如我所提到的,那裏的代碼非常龐大而複雜,所以任何有助於可讀性的小東西都會很好。 – 2013-02-22 19:04:02