使用PROC SQL作为IF / ELSE IF语句

时间:2016-11-08 17:27:44

标签: if-statement sas proc-sql

我正在尝试运行以下代码,但它无法正常运行。我发现问题在于每个case when都会覆盖下一个语句。

所以,我需要做的是IF/ELSE IF staetment,但我不知道如何在PROC-SQL中这样做

proc sql;
create table example
as select *,

case when B.variable = 'X'               then 1 else 0 end as variable_X,   
case when B.variable = 'Y'               then 1 else 0 end as variable_Y,   
case when B.variable = 'Z'               then 1 else 0 end as variable_Z,   
case when B.variable = 'W'               then 1 else 0 end as variable_W,   
case when B.variable = 'R'               then 1 else 0 end as variable_R,
case when B.variable = 'G'               then 1 else 0 end as variable_G,
case when B.variable = 'T'               then 1 else 0 end as variable_T,   
case when B.variable = 'U'               then 1 else 0 end as variable_U,
case when B.variable = 'P'               then 1 else 0 end as variable_P,   
case when B.variable = 'L'               then 1 else 0 end as variable_L

FROM my_table             as A
LEFT JOIN my_second_table as B
on A.KEY1=E.KEY1  and A.KEY2=E.KEY2
;

我已经尝试使用group by语句,但它不起作用。

P.S。:我的真实代码比我的例子大得多,有8 left join和更多变量。我刚刚发布了它的摘录。

1 个答案:

答案 0 :(得分:0)

在SAS中,如果你正在尝试做你在那里做的事情,你不应该用proc sql来做。您应该在数据步骤或proc transpose中执行此操作。

如果我有SASHELP.CLASS并希望每个年龄都成为旗帜,我可以这样做:

proc sql;
  select name, age,
    case when age=11 then 1 else 0 end as age_11,
    case when age=12 then 1 else 0 end as age_12
    from sashelp.class;
quit;

等。 - 很多代码,你硬编码了可能的值。或者:

data class;
  set sashelp.class;
  x=1;
run;

proc transpose data=class out=class_t prefix=age_; 
  by name;
  id age;
  var x;
run;

然后将其重新合并,但是您希望假设您有其他有用的数据。您可能已经拥有了一个可以为占位符x弹出的变量,而不是动态地制作一个变量。