如何在proc sql sas中编写lag()函数计算日期差

osh3o9ms  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(545)

我试图在SQLSAS中编写一个代码来计算用户被看到的天数差。
原始数据示例如下:

USER     DATE
User1    20200516
User1    20200513
User1    20200501
User2    20200515
User2    20200511

如何编写lag()函数,使输出表如下所示:

USER     DATE       PREV_DATE    DIFF
User1    20200516   20200513     3
User1    20200513   20200501     12
User2    20200515   20200511     4
of1yzvn4

of1yzvn41#

我不使用sas,所以请把我的答案作为使用sas的提示 lag 函数,其他问题,如日期转换或计算差异由您决定。这是postgres中的解决方案(重命名列以避免冲突):

with t(user_col,date_col) as (values
  ('User1', date '2020-05-16'),
  ('User1', date '2020-05-13'),
  ('User1', date '2020-05-01'),
  ('User2', date '2020-05-15'),
  ('User2', date '2020-05-11')
), lags as (
  select user_col
       , date_col
       , lag(date_col) over (partition by user_col order by date_col) as prev_date
  from t
)
select user_col, date_col, prev_date, date_col - prev_date as diff
from lags
where prev_date is not null
order by user_col asc, date_col desc

在这儿摆弄。
下一次请直接以cte(with子句)的形式提供示例输入。

esbemjvw

esbemjvw2#

sql没有延迟烘焙的概念,sas-sql不实现窗口函数或cte
使用自反连接和sas-sql自动重合并功能可以获得所需的结果集。

data have;
attrib
  user length=$8
  date length= 8 format=yymmdd10. informat=yymmdd10.
;
input USER DATE;
datalines;
User1    20200516
User1    20200513
User1    20200501
User2    20200515
User2    20200511
;

proc sql;
  create table want as
  select 
    LEFT.user
  , LEFT.date
  , RIGHT.date as PREV_DATE
  , LEFT.date - RIGHT.date as DIFF
  from
    have as LEFT
  left join
    have as RIGHT
  on
    LEFT.user = RIGHT.user
  where
    LEFT.date > RIGHT.date
  group by
    LEFT.date
  having
    DIFF = MIN(DIFF)
  order by
    LEFT.user, LEFT.date desc, RIGHT.date desc
  ;
jjhzyzn0

jjhzyzn03#

这是一种数据步方法

data have;
input USER $ DATE :anydtdte.;
format date yymmddn8.;
datalines;
User1 20200516
User1 20200513
User1 20200501
User2 20200515
User2 20200511
;

data want;
    merge have
          have(firstobs=2 rename=(date=prev_date user=_user));
    if user=_user;
    diff=date-prev_date;
    drop _:;
run;

相关问题