我有一张桌子,就像:
Order ID | Customer ID | Product ID | Recipient ID
1 | 2 | 3 | 4
2 | 4 | 6 | 7
3 | 4 | 6 | 8
4 | 9 | 6 | 8
5 | 9 | 6 | 8
6 | 2 | 8 | 4
7 | 3 | 8 | 4
8 | 3 | 8 | 5
我想就以下几点提出疑问:
我认为要运行的查询对于所有4人来说都是非常相似的,但是我很难理解如何开始。
发布于 2015-07-15 04:04:42
曾为同一收件人购买相同礼物的顾客(因此期望购买的次数超过一次):
SELECT customer_id, recipient_id, Product_ID
FROM table_a
GROUP BY customer_id, recipient_id, Product_ID
HAVING COUNT(*)>1;
顾客购买了不同的礼物给不同的接受者:逻辑:
首先找出所有唯一的数据组合。 recipients>1的计数表示超过一个收件人,而products>1的计数表示有超过一个product=>,所以比recipient=different收件人多一个product_id=more超过一个礼物,所以一定是不同的礼物。
SELECT customer_id, COUNT(recipient_id), COUNT(product_id)
FROM (
SELECT DISTINCT customer_id, recipient_id, product_id
FROM table_a ) b
GROUP BY customer_id
HAVING COUNT(recipient_id)>1 AND COUNT(product_id)>1;
曾为同一收件人购买不同礼品的顾客:
SELECT customer_id, recipient_id, COUNT(DISTINCT product_id)
FROM table_a
GROUP BY customer_id, recipient_id
HAVING COUNT(DISTINCT product_id)>1
顾客购买了相同的礼物给不同的收件人
SELECT customer_id, COUNT(DISTINCT recipient_id), product_id
FROM table_a
GROUP BY customer_id, product_id
HAVING COUNT(DISTINCT recipient_id)>1
https://stackoverflow.com/questions/31421199
复制相似问题