Calculate Datediff between rows in one column (with more than 2 records)

前端 未结 2 1811
盖世英雄少女心
盖世英雄少女心 2021-01-18 17:31

I have a table which has a column of dates which I want to find the difference between. I have been able to find off your site an answer that gets me the difference between

2条回答
  •  温柔的废话
    2021-01-18 17:36

    Change the correlated subquery so that it returns the greatest of the earlier Pstng_Date values for T1.Customer

    This query returned what you want when tested with your sample data in Access 2007.

    SELECT
        AllDays.Customer,
        AllDays.Pstng_Date,
        Nz(DateDiff("d",[PreviousDate],[Pstng_Date]), 0) AS Days_Between
    FROM
        (
            SELECT
                Customer,
                Pstng_Date,
                (
                    SELECT Max(Pstng_Date)
                    FROM SAPData AS T2
                    WHERE
                            T2.Customer = T1.Customer
                        AND T2.Pstng_Date < T1.Pstng_Date
                ) AS PreviousDate
            FROM SAPData AS T1
        ) AS AllDays;
    

    If you will be running the query from outside an Access session, the Nz() function will not be available. In that case, you could use an IIf() expression instead.

    IIf([PreviousDate] Is Null, 0, DateDiff("d",[PreviousDate],[Pstng_Date]))
    

提交回复
热议问题