我正在尝试编写一个SQL查询,该查询计算两次或两次以上购买的所有客户从购买到购买的平均天数:
Customer_ID | Average number of day
1033 | 175
11 | 334
1100 | 202.5
111 | 52.5
我成功显示了所有客户的所有购买日期,并计算了两次购买之间的购买天数。
SELECT Customer_ID, Order_Date Cur,
LAG(Order_Date, 1) OVER (ORDER BY Customer_ID) AS Previous,
DATEDIFF(day, LAG(Order_Date, 1) OVER (ORDER BY Customer_ID), Order_Date)
[Days Between Purchases]
FROM Orders
如何忽略每个客户的第一行并计算两次购买之间的平均值? (我必须在回答中使用LAG
答案 0 :(得分:1)
最简单的方法是聚合和一些算法:
SELECT CustomerId,
DATEDIFF(day, MIN(o.Order_Date), MAX(o.Order_date)) * 1.0 / NULLIF(COUNT(*) - 1, 0)
FROM Orders o
GROUP BY CustomerId
HAVING COUNT(*) >= 2;
从某种意义上说,“订单之间的平均天数”是一个棘手的问题。您认为您必须计算每个订单与下一个订单之间的差额。
实际上,您只需要将从第一个订单到最后一个订单的总时间除以订单数量即可。我可以让你弄清楚为什么会这样。
答案 1 :(得分:1)
您的脚本几乎可以正常运行。只需添加客户ID关系即可。否则,第一行所有有效客户都不会为NULL。
SELECT
cur.Customer_ID,
cur.Order_Date Cur,
previous.Order_Date Previous,
DATEDIFF(day, previous.Order_Date, cur.Order_Date) [Days Between purchases]
FROM tblDifference cur
LEFT OUTER JOIN tblDifference previous
ON cur.RowNumber = previous.RowNumber+1
AND cur.customer_id = previous.customer_id;