帮我编写 mySQL 查询语句,分析三个月复购率,复购金额,复购人数,购买金额,购买人数,,按月移动,非季度
时间: 2023-06-20 22:10:37 浏览: 99
假设你的表名为 `orders`,包含以下字段:`order_id`(订单ID),`user_id`(用户ID),`order_time`(下单时间),`order_amount`(订单金额)。
以下是计算三个月复购率、复购金额、复购人数、购买金额、购买人数的 mySQL 查询语句,按月移动:
```sql
SELECT
DATE_FORMAT(order_time, '%Y-%m') AS month,
COUNT(DISTINCT CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 AND repeat_count > 0 THEN user_id END) / COUNT(DISTINCT CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 THEN user_id END) AS repeat_rate,
SUM(CASE WHEN DATEDIFF(order_time, first_order_time) > 90 AND repeat_count > 0 THEN order_amount ELSE 0 END) AS repeat_amount,
COUNT(DISTINCT CASE WHEN DATEDIFF(order_time, first_order_time) > 90 AND repeat_count > 0 THEN user_id END) AS repeat_count,
SUM(CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 THEN order_amount ELSE 0 END) AS purchase_amount,
COUNT(DISTINCT CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 THEN user_id END) AS purchase_count
FROM (
SELECT
order_id,
user_id,
order_time,
order_amount,
MIN(order_time) OVER (PARTITION BY user_id) AS first_order_time,
COUNT(*) OVER (PARTITION BY user_id) - 1 AS repeat_count
FROM orders
) t
GROUP BY DATE_FORMAT(order_time, '%Y-%m')
ORDER BY month;
```
解释一下查询语句:
1. `MIN(order_time) OVER (PARTITION BY user_id)` 表示每个用户的第一次下单时间;
2. `COUNT(*) OVER (PARTITION BY user_id) - 1` 表示每个用户的下单次数减去第一次下单,即复购次数;
3. `CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 AND repeat_count > 0 THEN user_id END` 表示三个月内有复购的用户ID;
4. `CASE WHEN DATEDIFF(order_time, first_order_time) > 90 AND repeat_count > 0 THEN order_amount ELSE 0 END` 表示三个月后有复购的订单金额;
5. `CASE WHEN DATEDIFF(order_time, first_order_time) <= 90 THEN order_amount ELSE 0 END` 表示三个月内下的订单金额。
注意:上面的查询语句计算复购率时使用的是用户数,而不是订单数。计算复购率时,需要先确定每个用户的第一次下单时间,然后根据三个月内是否有复购来决定该用户是否算作复购用户。
阅读全文