连续行之间的日期差添加其他列

时间:2018-09-17 17:25:33

标签: sql ms-access

说我在Rishal的第二个表中添加了“成本差异”列(请参见下面的上一篇文章链接),我还将如何计算和显示它?

仅使用1001帐号,并将以下ID1 = $ 10,ID4 = $ 33和ID6 = $ 50分别添加到第一张表中,如何在Rishal的第二张表中显示结果$ 23和$ 17,以及其他已经有3列?

我已经使用了这段代码(来自GarethD),并想在其中插入“费用差异”列...谢谢,

SELECT  ID,
        AccountNumber,
        Date,
        NextDate,
        DATEDIFF("D", Date, NextDate)
FROM    (   SELECT  ID, 
                    AccountNumber,
                    Date,
                    (   SELECT  MIN(Date) 
                        FROM    YourTable T2
                        WHERE   T2.Accountnumber = T1.AccountNumber
                        AND     T2.Date > T1.Date
                    ) AS NextDate
            FROM    YourTable T1
        ) AS T

Date Difference between consecutive rows

1 个答案:

答案 0 :(得分:0)

我建议使用JOIN引入下一条记录:

SELECT T.*, DATEDIFF("D", t.Date, t.NextDate) as datediff,
       TNext.Amount, (Tnext.Amount - T.Amount) as amountdiff
FROM (SELECT T1.*,
             (SELECT MIN(Date) 
              FROM YourTable T2
              WHERE T2.Accountnumber = T1.AccountNumber AND
                    T2.Date > T1.Date
            ) AS NextDate
      FROM  YourTable as T1
     ) AS T LEFT JOIN
     YourTable as Tnext
     ON t.Accountnumber = tnext.Accountnumber AND t.Date = tnext.Accountnumber;