Hi,
The way to calculate the averages (in days) between the various orderdates per customer and sales order in SQL could be:
Code:
SELECT customer_id, sales_order_id,
avg(extend(order_date,YEAR TO DAY) - extend(
(SELECT order_date FROM table b
WHERE b.customer_id = a.customer_id
AND b.sales_order_id = a.sales_order_id -1),YEAR TO DAY))
FROM table a
WHERE customer_id = 1
AND sales_order_id > 1
GROUP BY 1, 2
ORDER BY 1, 2
This way all sales orders after the first one are selected with the number of days between the current and previous sales order.
If you want to use only the last interval you can add:
Code:
AND NOT EXISTS (SELECT 1 FROM table c
WHERE c.customer_id = a.customer_id
AND c.sales_order_id > a.sales_order_id)
to the query.
If you want to use this number to add to e.g. the current date you can extend the SELECT clause with:
Code:
SELECT customer_id, sales_order_id,
avg(extend(order_date,YEAR TO DAY) - extend(
(SELECT order_date FROM table b
WHERE b.customer_id = a.customer_id
AND b.sales_order_id = a.sales_order_id -1),YEAR TO DAY)) + today
Regards