Let's suppose I have two tables: customers
and orders
Orders have these columns:
order_created
customer_id
Customers have these columns:
id
name
email
I am trying to build a query to show me the average range of the latest customer orders, for example:
- get two latest orders from all customers (select only customers that have more than 1 order, of course)
- compare the dates and retrieve the average time from o1 to o2 (all customers)
I am not very experienced with MySQL, but so far I have managed to get the max value.
select max(o.order_created), c.id, c.name, c.email,
(date(max(o.order_created)) - date(min(o.order_created))) as date_interval
from orders o
inner join customers c
on c.id = o.customer_id
group by c.id
having date_interval > 0
min
doesn`t work, of course, because I need to retrieve the second max value, not the minimum. And after all that, it needs to retrieve an average value for all this query, which I have no clue how to build.
How can I approach this?
Thanks everybody.
@Edit I don`t think the duplicate mark solve my question