-2

有人可以帮我找到产品级别的第一次和第二次购买之间的平均时间。

这是我写的——

Select A.CustomerId,A.ProductId , A.OrderSequence, (Case WHEN OrderSequence = 1 THEN OrderDate END) AS First_Order_Date,
MAX(Case WHEN OrderSequence = 2 THEN OrderDate END) AS Second_Order_Date
From
(
Select t.CustomerId, t.ProductId, t.OrderDate,
Dense_RANK() OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate Asc) as OrderSequence  
From Transactions t (NOLOCK)
Where t.SiteKey = 01
Group by t.CustomerId, t.ProductId, t.OrderDate)
A
Where A.OrderSequence IN (1,2)
Group By A.Customer_Id, A.ProductId, A.OrderSequence, A.OrderDate

样本数据:

在此处输入图像描述

4

1 回答 1

0

它看起来像行编号,LEAD应该在这里为您解决问题。

  • NOLOCK除非你真的知道自己在做什么,否则不要使用
  • 目前还不清楚您是否希望结果也被分区CustomerId。如果没有,您可以在查询中的任何位置删除它
SELECT
  A.CustomerId,
  A.ProductId,
  AVG(DATEDIFF(day, OrderDate, NextOrderDate))
FROM
(
    SELECT
      t.CustomerId,
      t.ProductId,
      t.OrderDate,
      ROW_NUMBER() OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate) AS rn,
      LEAD(OrderDate) OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate) AS NextOrderDate
    FROM Transactions t
    WHERE t.SiteKey = '01'
) t
WHERE t.rn = 1
GROUP BY
  t.Customer_Id,
  t.ProductId;
于 2021-10-26T19:25:30.207 回答