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

问题描述 投票:-2回答:1

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

订单表包含列

Order_id
Customer_id
Order_Timestamp
Order_status

Order_status可以取值'success'或'failure'

mysql sql analytics
1个回答
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条件内的第二个子查询可确保同一客户在下个月内至少有一个订单。

© www.soinside.com 2019 - 2024. All rights reserved.