How to calculate date difference between different visits using SQL

2k Views Asked by At

I want to calculate the day difference between first visit and the second visit; second visit and third visits etc. per customer using SQL. Please assist.

For example, Customer A visited three times on 2016-01-03, 2016-01-06 and 2016-05-30 while customer B visited ten times with different dates.

Query

With cte as (Select customerid, VisitDate,
                    ROW_NUMBER() OVER(PARTITION BY CustomerID ORDER BY VisitDate) as rownum
             FROM visitTable V)
Select CustomerID, VisitDate, rownum, DateDiff(D,R1.VisitDate, R2.VisitDate) as NoOfDays
FROM cte R1
LEFT JOIN cte R2 ON R1.CustomerID = R2.CustomerID AND R1.rownum = 1 AND R2.rownum = 2 

Thank you

1

There are 1 best solutions below

0
On BEST ANSWER

I think you were pretty close to the right idea. Your join needs to compare row numbers. I also switched the order of your date diff but I didn't test it.

With cte as (
        Select  customerid, VisitDate,
                ROW_NUMBER() OVER(PARTITION BY CustomerID ORDER BY VisitDate) as rownum
        FROM    visitTable V
)
Select  R1.CustomerID, R1.VisitDate, R1.rownum,
        DateDiff(D,R2.VisitDate, R1.VisitDate) as NoOfDays  --this is days since last visit
FROM    cte R1  --current row
LEFT    JOIN cte R2 --previous visit - will result in null days for 1st row.
        ON  R1.CustomerID = R2.CustomerID
        AND R1.rownum - 1 = R2.rownum
order   by R1.CustomerID, R1.VisitDate;