Date Difference between consecutive rows

you ca also use LAG analytical function to get the desired results as :

Suppose below is your input table:

id  account_number  account_date
1     1001          9/10/2011
2     2001          9/1/2011
3     2001          9/3/2011
4     1001          9/12/2011
5     3001          9/18/2011
6     1001          9/20/2011


select id,account_number,account_date,
datediff(day,lag(account_date,1) over (partition by account_number order by account_date asc),account_date)
as day_diffrence
from yourtable;

Here is your output:

id  account_number  account_date    day_diffrence
1     1001           9/10/2011    NULL
4     1001           9/12/2011    2
6     1001           9/20/2011    8
2     2001           9/1/2011     NULL
3     2001           9/3/2011     2
5     3001           9/18/2011    NULL

SELECT  T1.ID, 
        T1.AccountNumber, 
        T1.Date, 
        MIN(T2.Date) AS Date2, 
        DATEDIFF("D", T1.Date, MIN(T2.Date)) AS DaysDiff
FROM    YourTable T1
        LEFT JOIN YourTable T2
            ON T1.AccountNumber = T2.Accountnumber
            AND T2.Date > T1.Date
GROUP BY T1.ID, T1.AccountNumber, T1.Date;

or

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

Tags:

Sql

Ms Access