首页 > 解决方案 > 在 sas 中使用 proq sql 进行数据操作

问题描述

我有下表

在此处输入图像描述

我计算 y 和 z 的标准偏差,直到从 2001 q4 到 2003 q2 。

我必须创建一个应该如下所示的新表

在此处输入图像描述

我尝试在 proc sql 中使用 case 语句,但它不起作用。任何帮助将不胜感激。

proc sql;
create table tablenew as
select
Date,
X,
case when Date >= "2003Q3" then (y+std(y)) else y end as y,
case when Date >= "2003Q3" then (z-std(z)) else z end as z
from have
;
quit;

但是在这里,计算整个列的标准偏差,我只想要 y 和 z 列的标准偏差,从 2001 q3 ​​到 2003 q2

标签: sas

解决方案


仅使用 SQL 只会使这个问题变得比它需要的更困难,但问题是您还需要将发送给 STD() 函数的值包装在 CASE 语句中。在这里,我将这些修剪后的值保存为它们自己的变量,这样你就可以看到发生了什么。

create table tablenew as
select
  Date
 ,X
 ,case when date >= '2003Q3' then y else . end as y_subset
 ,case when date >= '2003Q3' then z else . end as z_subset
 ,case when Date >= "2003Q3" then (y+std(calculated y_subset)) else y end as y
 ,case when Date >= "2003Q3" then (z-std(calculated z_subset)) else z end as z
from have
;

更容易将其分解为逻辑步骤,只需使用普通的 SAS 代码而不是 SQL。

proc summary data=have ;
   where date >= '2003Q3' ;
   var y z ;
   output out=std std=y_std z_std ;
run;
data want ;
   set have ;
   if _n_=1 then set std ;
   if date >= '2003Q3' then do;
     y=y+y_std;
     z=z-z_std;
   end;
run;

推荐阅读