编写SQL脚本,基于订单数据计算22年10月31日-22年11月11日活动期间新客和老客的购买人数、支付金额、各个品类及货品购买人数和购买金额;其中新客指22年10月30日前365天无购买行为消费者;老客指22年10月30日前365天有购买行为消费者,且在D11有购买行为
时间: 2024-01-24 09:17:34 浏览: 82
假设我们有以下表:
- `orders` 表,包含所有订单的信息,有字段 `order_id`(订单ID)、`user_id`(用户ID)、`product_id`(商品ID)、`category_id`(商品分类ID)、`order_date`(订单日期)和 `payment_amount`(支付金额);
- `users` 表,包含所有用户的信息,有字段 `user_id`(用户ID)和 `last_purchase_date`(最近一次购买日期)。
则可以编写如下SQL脚本来计算活动期间新客和老客的购买人数、支付金额、各个品类及货品购买人数和购买金额:
```
-- 新客购买人数和支付金额
SELECT COUNT(DISTINCT o.user_id) AS new_customers, SUM(o.payment_amount) AS new_payment_amount
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
WHERE o.order_date BETWEEN '2022-10-31' AND '2022-11-11'
AND u.last_purchase_date < DATE_SUB('2022-10-31', INTERVAL 365 DAY);
-- 老客购买人数和支付金额
SELECT COUNT(DISTINCT o.user_id) AS old_customers, SUM(o.payment_amount) AS old_payment_amount
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
WHERE o.order_date BETWEEN '2022-10-31' AND '2022-11-11'
AND u.last_purchase_date BETWEEN DATE_SUB('2022-10-31', INTERVAL 365 DAY) AND '2022-10-30';
-- 各个品类购买人数和支付金额
SELECT o.category_id, COUNT(DISTINCT o.user_id) AS category_customers, SUM(o.payment_amount) AS category_payment_amount
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
WHERE o.order_date BETWEEN '2022-10-31' AND '2022-11-11'
AND u.last_purchase_date BETWEEN DATE_SUB('2022-10-31', INTERVAL 365 DAY) AND '2022-10-30'
GROUP BY o.category_id;
-- 各个货品购买人数和支付金额
SELECT o.product_id, COUNT(DISTINCT o.user_id) AS product_customers, SUM(o.payment_amount) AS product_payment_amount
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
WHERE o.order_date BETWEEN '2022-10-31' AND '2022-11-11'
AND u.last_purchase_date BETWEEN DATE_SUB('2022-10-31', INTERVAL 365 DAY) AND '2022-10-30'
GROUP BY o.product_id;
```
需要注意的是,上述SQL脚本中使用了 `LEFT JOIN`,因为有些用户可能没有购买记录,但仍需要计算在内。同时,为了方便起见,日期格式统一使用了 `YYYY-MM-DD`。具体情况下需要根据实际的表结构和需求进行调整。
阅读全文