2

我正在尝试对下表进行查询(仅相关部分):

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

我想查看包含每个客户订单之间平均天数的 CustomerID 列表。我很好奇这是否可以使用基于纯集合的解决方案来完成,或者是否需要游标/临时表解决方案。

4

1 回答 1

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
于 2010-12-01T17:39:50.103 回答