查找SQL Server中的日期之间的间隔

时间:2015-05-03 08:53:46

标签: sql sql-server datediff

我有一张包含超过500万行销售交易的表格。我想找到每个客户最近三次购买之间的日期间隔总和

假设我的表看起来像这样:

CustomerID        ProductID             ServiceStartDate     ServiceExpiryDate     
   A                X1                     2010-01-01             2010-06-01
   A                X2                     2010-08-12             2010-12-30
   B                X4                     2011-10-01             2012-01-15
   B                X3                     2012-04-01             2012-06-01
   B                X7                     2012-08-01             2013-10-01
   A                X5                     2013-01-01             2015-06-01

我正在寻找的结果可能如下:

CustomerID        IntervalDays 
    A                  802
    B                  135               

我知道查询需要首先检索每个客户的3个重新发送的交易(基于ServiceStartDate),然后计算他/她交易的startDateExpiryDate之间的间隔。

1 个答案:

答案 0 :(得分:1)

假设没有重叠,我想你想要这个:

select customerId,
       sum(datediff(day, ServiceStartDate, ServieEndDate) as Intervaldays
from (select t.*, row_number() over (partition by customerId
                                     order by ServiceStartDate desc) as seqnum
      from table t
     ) t
where seqnum <= 3
group by customerId;