如何从数据表中获取客户ID、总消费额及最高消费商品?
解决方案
要同时获取客户ID、总消费额和消费最高的商品名称,你需要结合窗口函数和分组聚合来实现,具体实现如下:
完整SQL查询
WITH item_spend AS ( SELECT customer_id, item_name, item_number * item_price AS item_total, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY item_number * item_price DESC) AS rn FROM temp ), customer_total AS ( SELECT customer_id, SUM(item_number * item_price) AS amount_spent FROM temp GROUP BY customer_id ) SELECT ct.customer_id, ct.amount_spent, isp.item_name AS top_item FROM customer_total ct JOIN item_spend isp ON ct.customer_id = isp.customer_id WHERE isp.rn = 1;
关键逻辑说明
item_spendCTE:计算每个客户每款商品的实际消费额,并用ROW_NUMBER()按客户分组,对单商品消费额降序排序,排名为1的记录就是该客户消费最高的商品。如果存在多款商品消费额并列最高的场景,可替换为RANK(),这样会返回所有并列第一的商品。customer_totalCTE:统计每个客户的总消费额,和你的原始查询逻辑一致。- 最后通过客户ID关联两个CTE,筛选出排名为1的商品,得到完整的目标字段。
内容的提问来源于stack exchange,提问作者Oleg Romanov
相关产品推荐
相关产品推荐

