如何计算不同行中当前日期和上一个日期之间的差异

时间:2018-05-18 20:25:47

标签: sql date teradata-sql-assistant

您好我想使用sql teradata assistant

计算不同行中日期之间的差异

我的表看起来像这样

create table test (
    id INT,
    Dx varchar(10)
    Dx_date date);

    insert into TEST values(1,'E14','2015-05-03');
insert into TEST values(1,'E15','2013-05-06');
insert into TEST values(1,'E15','2016-03-03');
insert into TEST values(2,'E15','2012-03-04');
insert into TEST values (3,'E144','2011-03-04');
insert into TEST values  (3,'E122','2011-02-04');

比使用此代码计算每行之间的日期差异

select id,
            dx, 
            Date_dx, 
            zeroifnull (MDIFF(Date_dx,1,id,dx)
            from TEST
            group by id;

但它给我错误的结果

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

  

窗口功能应该可以轻松实现。

天的日期差异

  Select *
 ,DateDiff(DD, Dx_date, Lag(Dx_Date) Over (Order By Dx_date)) DateDiff
 From test

虽然您没有指定,但是您尝试计算日期,表明您很多人有兴趣计算每个ID的日期,所以;

Select  *
        ,DateDiff(DD, Dx_date, Lag(Dx_Date) Over (Partition by id Order By Dx_date)) DateDiff
From test

注意:您可能需要根据需要编辑日期函数。

答案 1 :(得分:0)

试试这个:

 select id, dx, datediff(day, lastdate, date_dx) datedifference from (
    select id,
                dx, 
                Date_dx, 
                lag(Date_dx,1,null) over(order by id)lastdate
                from TEST)A

答案 2 :(得分:0)

我找到了解决方案

select id ,dx,Dx_date,
       zeroifnull(dx_date-min(dx_date) over (partition by id order by dx_date rows 
       between 1 preceding and 1 preceding )) as difference _dx_date
from TEST;

谢谢