2016-11-22 46 views
0

我想知道是否有可能由於單個CASE而執行多個分配。也就是說,不是有兩個CASE語句,而是有一個CASE語句,它有一個'then-do-end'結構。SAS:PROC SQL作爲單個CASE的結果的多個分配

例如,如何根據單個CASE語句中的x將值分配給thing1thing2

data example; 
    input x $; 

    datalines; 
    A 
    A 
    A 
    B 
    B 
    ; 
run; 

proc sql; 
    create table make_two_from_one as 
    select * 
    , case 
     when x = 'A' then 'Result1A' 
     when x = 'B' then 'Result1B' 
     else 'Error' 
    end as thing1 
    , case 
     when x = 'A' then 'Result2A' 
     when x = 'B' then 'Result2B' 
     else 'Error' 
    end as thing2 
    from example 
    ; 
quit; 
+1

不幸的是,這不是SQL的工作原理。 –

+0

你可以在組中添加計數嗎?然後選擇價值和它的計數的組合? (對於第一部分,請看這裏:http://stackoverflow.com/questions/17006765/get-a-the-row-number-in-a-data-step-using-sas) – johnjps111

+0

或者你可以這樣做一個數據步驟,因爲SQL沒有任何數據步驟難以複製的東西。 – Reeza

回答

1

Case語句構造一個變量。

爲了您的例子中,你可以試試這個,用案例的一個聲明:

data example; 
    input x $; 

    datalines; 
    A 
    A 
    A 
    B 
    B 
    ; 
run; 

proc sql; 
    create table make_two_from_one_2 as 
    select * 
    , case 
     when x = 'A' then 'Result1A,Result2A' 
     when x = 'B' then 'Result1B,Result2B' 
     else 'Error' 
    end as thing0 

    from example 
    ; 
quit; 

data example1(drop=thing0); 
    set make_two_from_one_2; 
    thing1=scan(thing0,1,','); 
    thing2=scan(thing0,2,','); 
run; 
0

在你的情況,也許你可以試試這個:

proc sql; 
    create table make_two_from_one as 
    select * 
    , case 
     when x = 'A' then 'Result1A' 
     when x = 'B' then 'Result1B' 
     else 'Error' 
    end as thing1, 
    translate(calculated thing1,'2','1') as thing2 
    from example 
    ; 
quit; 
0

我個人認爲這方面的需求,即爲了克服繁瑣的語法障礙和可以在一個地方維護的東西,對於SAS宏來說是一個很好的用例。

宏版本也避免瞭解析的危險,很好地列表,並且沒有類型假設。

%macro _case(when_A, when_B, error='Error'); 
     case 
      when x = 'A' then &when_A 
      when x = 'B' then &when_B 
      else &error 
     end 
%mend; 

proc sql; 
    create table make_two_from_one_v2 as 
    select * 
    , %_case('Result1A', 'Result1B') as thing1 
    , %_case('Result2A', 'Result2B') as thing2 
    from example 
    ; 
quit; 
3

只是爲了完整性,這是在數據步驟簡單,使用selectwhendootherwise。或者您可以使用if,then,do,else

data want; 
set example; 
select (x); 
    when ('A') do; 
     thing1 = 'Result1A'; 
     thing2 = 'Result2A'; 
     end; 
    when ('B') do; 
     thing1 = 'Result1B'; 
     thing2 = 'Result2B'; 
     end; 
    otherwise do; 
     thing1 = 'Error'; 
     thing2 = 'Error'; 
     end; 
end; 
run; 
+0

其他答案提供更通用的解決方案,但這是針對特定原始問題的最佳答案。也就是說,如果你有一個沒有合併的單個表的線性遍歷,沒有什麼比數據步驟更勝一籌。當您需要根據現有列的值添加多個列時,這也是最清晰優雅的代碼。 – Leo