如何统计同一客户购买的产品组合数量?
统计同一客户的产品组合数量
原始数据
| Customer_nr | Product |
|---|---|
| 11111 | Table |
| 22222 | Sofa |
| 333333 | Table |
| 444444 | Closet |
| 11111 | Bed |
需求
统计同一客户购买的产品组合数量,输出格式如下:
| Product A | Product B | Count of combination |
|---|---|---|
| Table | Bed | 245 |
(注:245表示同时购买Table和Bed的客户数量)
解决方案(SQL实现)
通过自连接表并分组统计,可高效实现需求,同时避免重复计数同一组合:
SELECT t1.Product AS `Product A`, t2.Product AS `Product B`, COUNT(DISTINCT t1.Customer_nr) AS `Count of combination` FROM customer_purchases t1 JOIN customer_purchases t2 ON t1.Customer_nr = t2.Customer_nr AND t1.Product < t2.Product GROUP BY t1.Product, t2.Product;
代码说明
- 自连接表
customer_purchases,关联同一客户的购买记录 t1.Product < t2.Product确保每个产品组合仅统计一次(如Table-Bed不会重复转为Bed-Table)COUNT(DISTINCT t1.Customer_nr)统计每个组合对应的唯一客户数,排除同一客户多次购买的重复计数
示例结果
用提供的测试数据运行上述SQL,会得到:
| Product A | Product B | Count of combination |
|---|---|---|
| Bed | Table | 1 |
内容的提问来源于stack exchange,提问作者aksent1344
相关产品推荐
相关产品推荐

