如何在SQL中计算平均日期出现频率

时间:2010-12-01 17:18:08

标签: tsql sql-server-2008 datetime frequency

我正在尝试在下表中生成查询(仅限相关部分):

Create Table [Order] (
  OrderID int NOT NULL IDENTITY(1,1),
  CreationDate datetime NOT NULL,
  CustomerID int NOT NULL
)

我希望看到每个客户在订单之间的平均天数的CustomerID列表。我很好奇是否可以使用基于纯集的解决方案或者如果需要游标/临时表解决方案。

1 个答案:

答案 0 :(得分:3)

;WITH base AS
     ( 
     SELECT  CustomerID,
             ROW_NUMBER() over (partition BY CustomerID ORDER BY CreationDate, OrderID) AS rn
     FROM     [Order]
     )
SELECT   b1.CustomerID,
         AVG(DATEDIFF(DAY,b1.CreationDate, b2.CreationDate) )
FROM     base b1
         JOIN base b2
         ON       b1.CustomerID=b2.CustomerID
         AND      b2.rn        =b1.rn+1
GROUP BY b1.CustomerID