我有一个名为的 SQL 表main_table
:
编号 | 产品编号 | 购买ID | 购买者 ID ---+------------+-------------+------------- 1 | 1 | 1 | 1 2 | 1 | 2 | 1 3 | 1 | 3 | 1 4 | 1 | 4 | 2 5 | 1 | 5 | 2 6 | 1 | 6 | 3 7 | 2 | 1 | 1 8 | 2 | 4 | 2 9 | 2 | 5 | 2 10 | 2 | 7 | 2 11 | 2 | 8 | 2 12 | 2 | 6 | 3 13 | 2 | 9 | 3 14 | 2 | 10 | 3 15 | 2 | 11 | 3 16 | 2 | 12 | 4 17 | 2 | 13 | 4
我需要分组product_id
并找到四件事:
- # 购买
- #购买者
- #重复购买
- #重复购买者
所以前3个比较简单...
SELECT FROM `main_table`
product_id,
COUNT(DISTINCT `purchase_id`) AS `purchases`,
COUNT(DISTINCT `purchaser_id`) AS `purchasers`,
(COUNT(DISTINCT `purchase_id`) - COUNT(DISTINCT `purchaser_id`)) AS `repeat_purchases`,
(??????) AS `repeat_purchasers`
GROUP BY product_id
ORDER BY product_id ASC
什么是??????
为了得到下表:
product_id | purchases | purchasers | repeat_purchases | repeat_purchasers
-----------+-----------+------------+------------------+------------------
1 | 6 | 3 | 3 | 2
2 | 11 | 4 | 7 | 3