编写SQL脚本,基于订单数据计算22年D11期间新客和老客的购买人数、支付金额、各个品类及货品购买人数和购买金额;其中新客指D11前一年无购买行为消费者;老客指D11前一年有购买行为消费者,且在D11有购买行为
时间: 2024-01-24 13:17:32 浏览: 80
通过分析订单商品数据模型
假设订单数据存在一个名为"orders"的表中,包含以下字段:
- order_id:订单ID
- customer_id:顾客ID
- order_date:订单日期
- payment_amount:支付金额
- product_category:产品类别
- product_name:产品名称
则可以编写如下SQL脚本来计算22年D11期间新客和老客的购买人数、支付金额、各个品类及货品购买人数和购买金额:
```
SELECT
-- 新客购买人数
COUNT(DISTINCT o.customer_id) AS new_customer_count,
-- 老客购买人数
COUNT(DISTINCT CASE WHEN p.last_order_date < '2021-11-01' THEN o.customer_id END) AS old_customer_count,
-- 新客支付总金额
SUM(CASE WHEN p.last_order_date IS NULL THEN o.payment_amount END) AS new_customer_payment_amount,
-- 老客支付总金额
SUM(CASE WHEN p.last_order_date < '2021-11-01' THEN o.payment_amount END) AS old_customer_payment_amount,
-- 各个品类购买人数
COUNT(DISTINCT CASE WHEN p.last_order_date < '2021-11-01' THEN o.customer_id END) AS old_customer_count,
COUNT(DISTINCT CASE WHEN p.last_order_date IS NULL THEN o.customer_id END) AS new_customer_count,
-- 各个品类购买金额
SUM(CASE WHEN p.last_order_date < '2021-11-01' THEN o.payment_amount END) AS old_customer_payment_amount,
SUM(CASE WHEN p.last_order_date IS NULL THEN o.payment_amount END) AS new_customer_payment_amount,
o.product_category,
-- 货品购买人数
COUNT(DISTINCT CASE WHEN p.last_order_date < '2021-11-01' THEN o.customer_id END) AS old_customer_count,
COUNT(DISTINCT CASE WHEN p.last_order_date IS NULL THEN o.customer_id END) AS new_customer_count,
-- 货品购买金额
SUM(CASE WHEN p.last_order_date < '2021-11-01' THEN o.payment_amount END) AS old_customer_payment_amount,
SUM(CASE WHEN p.last_order_date IS NULL THEN o.payment_amount END) AS new_customer_payment_amount,
o.product_name
FROM
orders o
LEFT JOIN
(
-- 每个顾客的最后一次订单日期
SELECT
customer_id,
MAX(order_date) AS last_order_date
FROM
orders
WHERE
order_date < '2022-01-01'
GROUP BY
customer_id
) p ON o.customer_id = p.customer_id
WHERE
o.order_date BETWEEN '2022-01-01' AND '2022-01-31'
GROUP BY
o.product_category,
o.product_name;
```
上述SQL脚本使用LEFT JOIN语句将每个顾客的最后一次订单日期与订单数据进行关联,从而判断该顾客是否为新客或老客。然后,根据条件分别计算新客和老客的购买人数、支付金额、各个品类及货品购买人数和购买金额。最后,按照产品类别和产品名称进行分组,得到每个类别和货品的购买人数和购买金额。
阅读全文