【发布时间】:2019-08-25 13:02:47
【问题描述】:
我试图通过查找最近的订单和第二个最近的订单之间的时间差,然后将该差添加到最近的订单中来估计来自回头客的新订单的时间。
我一直在尝试限制和偏移,但这会返回每一行的总括日期。我在想我需要做一个横向连接,但不知道如何正确实现它。当我尝试这样做时,我没有收到任何输出。
select public.orders.customer_id,
max(public.orders.created_at) as last_order_date,
(select created_at from public.orders group by created_at order by created_at desc limit 1 offset 1) as second_last
from public.orders
inner join
(select
customer_id, count(*)
from public.orders
where status = 'fulfilled'
group by public.orders.customer_id
having count(customer_id) >1) repeat_customers
on public.orders.customer_id = repeat_customers.customer_id
group by public.orders.customer_id;
我希望 second_last 字段由每个 customer_id 的第二个最近日期填充,但输出是整个表的第二个最近日期,导致每个条目的日期相同。
【问题讨论】:
标签: postgresql