1

您好我想使用 sql teradata 助手计算不同行中日期之间的差异

我的桌子看起来像这样

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;

但它给了我错误的结果

感谢您的帮助

4

3 回答 3

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

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

于 2018-05-18T20:37:43.763 回答
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;

谢谢

于 2018-05-21T14:32:43.480 回答
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
于 2018-05-18T20:33:57.527 回答