[编写MySQL查询以获取不同用户的数量,这些用户于2016年4月首次成功下订单,并在首次订购日期后30天内成功第二次下订单。
订单表包含列
Order_id
Customer_id
Order_Timestamp
Order_status
Order_status可以取值'success'或'failure'
这里是使用相关子查询和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
条件内的第二个子查询可确保同一客户在下个月内至少有一个订单。