如何使用SQL计算不同访问之间的日期差异

时间:2016-12-21 19:32:56

标签: sql sql-server datediff

我想计算第一次访问和第二次访问之间的日差;每个客户使用SQL进行第二次访问和第三次访问等。请协助。

例如,客户A访问了三次  2016-01-03,2016-01-06和2016-05-30,而客户B访问了十次不同的日期。

查询

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 

谢谢

1 个答案:

答案 0 :(得分:1)

我认为你非常接近正确的想法。您的联接需要比较行号。我也改变了你的日期差异的顺序,但我没有测试它。

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;