2016-11-22 49 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