【问题标题】:How to find whether the same customers who ordered this month also ordered the next month?如何查找本月订购的同一客户是否也订购了下个月?
【发布时间】:2021-01-05 18:31:51
【问题描述】:

我有一个订单表

Order_id  User_id  Order_date
 1        32        2020-07-19
 2        24        2020-07-21
 3        27        2020-07-27
 4        24        2020-08-14
 5        32        2020-08-18
 6        32        2020-08-19
 7        58        2020-08-20

现在我想知道有多少用户在第一个月订购了下个月也订购了。在这种情况下,user_id 的 32,24,27 是在第 7 个月订购的,但只有 24 和 32 是在下个月订购的。

我希望结果是这样的:

Date   Retained_Users  Total_users
2020-07     Null            3
2020-08      2              3

我迷路了。有人可以帮我解决这个问题吗?

【问题讨论】:

标签: mysql sql datetime count window-functions


【解决方案1】:

在 MySQL 8.0 中,您可以使用窗口函数来做到这一点:

select 
    order_month, 
    count(distinct case when cnt_orders_last_month > 0 then user_id end) retained_users,
    count(distinct user_id) total_users
from (
    select 
        user_id, 
        date_format(order_date, '%Y-%m-01') as order_month,
        count(*) over(
            partition by user_id
            order by date(date_format(order_date, '%Y-%m-01'))
            range between interval 1 month preceding and interval 1 day preceding
        ) cnt_orders_last_month
    from mytable
) t
group by order_month

逻辑在于窗口函数的范围规范;它按月记录订单,并统计客户上个月下了多少订单。然后剩下要做的就是聚合和统计不同的用户。

Demo on DB Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2018-03-04
    • 2023-01-23
    • 1970-01-01
    • 2019-02-27
    • 2014-02-14
    • 2021-10-17
    相关资源
    最近更新 更多