SAS:使用PROC SQL将日期变量写入SAS数据集

时间:2017-03-27 03:44:46

标签: sql macros sas proc-sql

我正在处理SAS中的一段代码,旨在将给定时间序列数据列中的最后一个非空值及其相应日期拉出,然后将它们插入到新数据集中。 SQL似乎是迄今为止最简单的方法,因此我一直在使用它。

我读取的数据集称为rtchg1,是从早期代码中的.xlsx电子表格导入的。它由日期变量和一堆时间序列变量组成。

data rtchg1;
set rtchg1;
where date between '1FEB1959'd and '1OCT1998'd;
run;

我写的表是使用一些简单的SQL创建的预测:

PROC SQL ;
    CREATE TABLE Forecasts
    (Date date,      
     Forecast num);
run;    

我之前已经格式化了'日期'更复杂,遇到同样的问题。如果我在这里做错了,请告诉我,有关如何改进我的代码的任何建议都表示赞赏。

最后,我一直在开发以下宏来提取数据:

%macro scoreprep(readtable,datevar,writetable); 
%do i=1 %to 3;

    %let currentvar=%scan(&periods,&i);

    proc sql;
        select &datevar, &currentvar into :date1, :LEI
        from &readtable
        where &currentvar is not null
        having &datevar=max(&datevar);

        insert into &writetable (Date, Forecast)
            values ("&date1"d, &LEI);
    quit;

%end;
%mend;

%scoreprep(rtchg1,date,Forecasts); 

现在只有1到3才能在没有太多等待时间的情况下测试它等等。这里的所有内容似乎都完美无缺,除了将日期变量插入表中。当我删除日期变量并输入& LEI时,它将其写入Forecasts表而没有任何问题。当我按原样运行代码时,我收到以下错误:

错误:日期/时间/日期时间常数无效" 10/01/1968" d。

不确定从哪里开始,无论我在哪里尝试转换宏变量的格式似乎都没有正常工作。建议将不胜感激。此外,如果您在我的代码中看到任何您不喜欢的内容,请随意批评。我知道更简单的方法在Excel中执行此操作,但这种方式更有趣:)

2 个答案:

答案 0 :(得分:1)

由于您将值拉入字符串,因此需要告诉SAS如何将该字符串转换回日期。明确您的转化方式。首先生成宏变量,然后生成VALUES()语句。因此,如果预测是一个数字,那么这应该只有最小的精度损失。

select put(&datevar,date9.) ,put(&currentvar,best32.) into :date1 ,:LEI
...
values ("&date1"d, &LEI)

但如果它是一个字符变量,那么你可能想要使用它。

select put(&datevar,date9.), quote(&currentvar) into :date1,:LEI
...
values ("&date1"d, &LEI)

还要确保您用作DATE源的变量实际上具有DATE值而不是DATETIME值。如果具有DATETIME值,则可以使用DTDATE格式以正确的格式生成宏变量。或者使用datepart()函数仅提取日期值。

请注意,将数据放入宏变量是没有意义的,以便稍后可以将其重新放入数据中。所以你可以使用PROC APPEND。

%macro scoreprep(readtable,datevar,writetable);
%local currentvar i ;
%do i=1 %to %sysfunc(countw(&periods));
  %let currentvar=%scan(&periods,&i);
proc sql;
  create table to_add as
    select &datevar as date 
         , &currentvar as forecast
    from &readtable
    where &currentvar is not null
    having &datevar=max(&datevar)
  ;
quit;
proc append data=to_add base=&writetable force ;
run;

%end;
%mend;

%scoreprep(rtchg1,date,Forecasts);

甚至只使用SQL代码插入查询结果。

insert into &writetable (date,forecast)
  select &datevar, &currentvar
    from &readtable
    where &currentvar is not null
    having &datevar=max(&datevar)
;

答案 1 :(得分:0)

尝试更改此行,看看是否有帮助:

    select &datevar format=date9., &currentvar into :date1, :LEI