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
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.