帮我编写 mySQL 查询语句,分析三个月复购率,复购金额,复购人数,购买金额,购买人数,按月移动,非季度
时间: 2023-06-20 13:10:11 浏览: 157
假设我们有一个名为order的表,包含以下字段:
- order_id 订单号
- user_id 用户ID
- order_date 订单时间
- amount 订单金额
查询语句如下:
```
SELECT
DATE_FORMAT(order_date, '%Y-%m') AS month,
COUNT(DISTINCT user_id) AS purchase_users,
SUM(amount) AS purchase_amount,
COUNT(DISTINCT IF(DATEDIFF(order_date, first_order_date) <= 90, user_id, NULL)) AS repeat_purchase_users,
SUM(IF(DATEDIFF(order_date, first_order_date) <= 90, amount, 0)) AS repeat_purchase_amount,
COUNT(DISTINCT IF(DATEDIFF(order_date, first_order_date) <= 60, user_id, NULL)) AS repeat_within_60_days_users,
SUM(IF(DATEDIFF(order_date, first_order_date) <= 60, amount, 0)) AS repeat_within_60_days_amount,
COUNT(DISTINCT IF(DATEDIFF(order_date, first_order_date) <= 30, user_id, NULL)) AS repeat_within_30_days_users,
SUM(IF(DATEDIFF(order_date, first_order_date) <= 30, amount, 0)) AS repeat_within_30_days_amount
FROM
(SELECT
user_id,
MIN(order_date) AS first_order_date
FROM
order
GROUP BY user_id) AS first_orders
JOIN order ON first_orders.user_id = order.user_id
GROUP BY month;
```
解释一下上面的语句:
1. 首先使用子查询 `first_orders` 找到每个用户的第一次订单时间。
2. 然后将 `first_orders` 与 `order` 表联接,计算每个月的指标。
3. 使用 `DATE_FORMAT` 函数将订单时间转换为年-月格式。
4. 使用 `DISTINCT` 关键字计算唯一用户数。
5. 使用 `IF` 函数在特定日期范围内计算指标。
6. 使用 `SUM` 函数计算订单金额总和。
上面的语句计算了三个月内的复购率、复购金额和复购人数,并且可以轻松地根据需要调整日期范围。
阅读全文