oracle 计算每个客户的订单之间的平均时间

ctehm74n  于 2023-08-03  发布在  Oracle
关注(0)|答案(5)|浏览(147)

我找遍了,但似乎找不到如何计算每个客户的平均订单间隔时间。使用Oracle SQL Developer。我试过使用lag()函数,但没有成功。
下面的示例数据显示了在3个不同场合购买的客户。所有购买之间的平均时间为7.5天((6+9)/2)。

CustID   OrderDate 
-------  ---------
1000000  14-AUG-12
1000000  23-AUG-12
1000000  29-AUG-12

字符串
那么,如何计算每个客户的平均值?
任何帮助都将不胜感激。

omtl5h9j

omtl5h9j1#

如果只需要平均值,那么我认为你可以通过查看最小和最大日期,然后按订单之间的间隔数进行潜水,来完成一个没有窗口函数的简单查询:

SELECT CustID, (MAX(OrderDate) - MIN(OrderDate)) / (COUNT(*) - 1)
  FROM Orders
 GROUP BY CustID
HAVING COUNT(*) > 1

字符串

tzxcd3kk

tzxcd3kk2#

这里的关键是lag解析函数

select cust_id , avg(orderdate - lag_orderdate) as avg_time_between_orders
from (
    select cust_id , orderDate , lag(orderdate) over (partition by cust_id) as lag_orderdate
    from  orders )

字符串

nwlqm0z1

nwlqm0z13#

LAG解析函数肯定是答案,但查询应该更像这样:

SELECT CustID, AVG(OrderDate - PriorDate)
FROM (
  SELECT
    CustID,
    OrderDate,
    LAG(OrderDate) OVER (PARTITION BY CustID ORDER BY OrderDate) as PriorDate
  FROM Orders)
GROUP BY CustID

字符串

smdncfj3

smdncfj34#

使用艾德的答案作为起点,使用CTE获得所有订单的平均值。

WITH Sales_CTE (CustomerId, OrderDays, OrderCount)
    AS
    (
    SELECT CustomerId, (datediff(day,Min(OrderTime),Max(OrderTime))) / (COUNT(*) - 1) AS OrderDays, COUNT(*) AS OrderCount
      FROM tblStoreOrders  GROUP BY CustomerId HAVING COUNT(*) > 1  
    )
    SELECT Avg(OrderDays) FROM Sales_CTE

字符串

vsnjm48y

vsnjm48y5#

Select customers.customerName, customers.CustomerNumber, T.date_diff as date_diff
 from customers 
join
(SELECT customerNumber, avg(datediff(shippedDate, orderDate))  as date_diff FROM classicmodels.orders group by customerNumber) AS T
on 
customers.customerNumber = T.customerNumber
order by date_diff

字符串

相关问题