Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the average time between orders for each customer

Tags:

sql

oracle

I've searched all over but cant seem to find how to calculate the average time between orders for each customer. I'm using Oracle SQL Developer. Ive tried using the lag() function with no joy.

Example data below shows a customer bought on 3 separate occasions. The average time between all purchases is 7.5 days ((6+9)/2).

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

So how do I calculate that average for each customer?

any help would be much appreciated.

like image 453
user2335923 Avatar asked Dec 03 '22 23:12

user2335923


2 Answers

If only the mean average is needed then I think you can get away with a simple query without window functions by looking at the min and max dates and then diving by the number of gaps between orders:

SELECT CustID, (MAX(OrderDate) - MIN(OrderDate)) / (COUNT(*) - 1)
  FROM Orders
 GROUP BY CustID
HAVING COUNT(*) > 1
like image 186
Ed Plese Avatar answered Jan 30 '23 07:01

Ed Plese


the key here is the lag analytic function

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 )
like image 44
haki Avatar answered Jan 30 '23 07:01

haki