查询以获取30天内第二次成功订购的客户的数量

时间:2020-01-07 12:15:51

标签: mysql sql analytics

编写一个MySQL查询以获取不同用户的数量,这些用户于2016年4月首次成功下订单,并在首次订购日期起30天内获得第二次成功订单。

“订单”表包含列

Order_id
Customer_id
Order_Timestamp
Order_status

Order_status可以使用值“成功”或“失败”

1 个答案:

答案 0 :(得分:0)

这是使用相关子查询和exists的一种方法:

select distinct o.customer_id
from orders o
where 
    o.order_timestamp = (
        select min(order_timestamp) from orders o1 where o1.customer_id = o.customer_id
    ) 
    and o.order_timestamp >= '2016-04-01' 
    and o.order_timestamp < '2016-05-01'
    and exists (
        select 1
        from orders o1
        where 
            o1.customer_id = o.customer_id 
            and o1.order_timestamp > o.order_timestamp
            and o1.order_timestamp <= o.order_timestamp + interval 1 month
    )

每个客户的第一个订单上的第一个相关子查询过滤器,并且以下条件确保它属于预期的月份;在exists条件内的第二个子查询可确保同一客户在下个月内至少有一个订单。

相关问题