判断表中是否有这个顾客,如果有,就这个顾客是否为VIP客户,如果是VIP客户,就把他最近一年的消费总金额按商品类别查询出来。
假设表的名称是 customers 和 transactions,其中:
customers表包含顾客信息,字段包括customer_id(顾客 ID)、is_vip(是否为 VIP 客户,1 表示是,0 表示否)。transactions表包含交易记录,字段包括customer_id(顾客 ID)、transaction_date(交易日期)、amount(交易金额)、product_category(商品类别)。
SQL 语句
SELECT
CASE
WHEN c.customer_id IS NULL THEN 'Customer does not exist'
WHEN c.is_vip = 0 THEN 'Customer is not a VIP'
ELSE
JSON_OBJECTAGG(
t.product_category,
SUM(t.amount)
) AS total_amount_by_category
END AS result
FROM
(SELECT 123 AS customer_id) AS input_customer -- 替换 123 为目标顾客的 ID
LEFT JOIN customers c ON input_customer.customer_id = c.customer_id
LEFT JOIN transactions t
ON input_customer.customer_id = t.customer_id
AND t.transaction_date >= NOW() - INTERVAL 1 YEAR -- 最近一年的交易记录
WHERE
c.customer_id IS NOT NULL -- 确保顾客存在
GROUP BY
c.customer_id, c.is_vip;
逻辑解释
-
判断顾客是否存在:
- 使用
LEFT JOIN将输入的顾客 ID 与customers表关联,如果c.customer_id为NULL,则表示顾客不存在。
- 使用
-
判断是否为 VIP 客户:
- 如果
c.is_vip = 0,则表示顾客不是 VIP。
- 如果
-
查询最近一年的消费总金额按商品类别分类:
- 如果顾客是 VIP,则通过
transactions表查询最近一年的交易记录,并按product_category分组,计算每个类别的消费总金额。 - 使用
JSON_OBJECTAGG将结果以 JSON 格式返回(如果不需要 JSON 格式,可以改为普通分组查询)。
- 如果顾客是 VIP,则通过
示例结果
假设输入的顾客 ID 是 123:
- 如果顾客不存在:
result: 'Customer does not exist' - 如果顾客存在但不是 VIP:
result: 'Customer is not a VIP' - 如果顾客是 VIP:
result: {"Electronics": 5000, "Clothing": 2000, "Books": 1000}
注意事项
- 替换
123为目标顾客的 ID。 - 如果你的数据库不支持
JSON_OBJECTAGG,可以改为普通分组查询:SELECT product_category, SUM(amount) AS total_amount FROM transactions WHERE customer_id = 123 AND transaction_date >= NOW() - INTERVAL 1 YEAR GROUP BY product_category;

被折叠的 条评论
为什么被折叠?



