1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客
Customers 表:
Column Name | Type |
---|---|
customer_id | int |
customer_name | varchar |
Orders 表:
Column Name | Type |
---|---|
order_id | int |
customer_id | int |
product_name | varchar |
请你编写解决方案,报告购买了产品 “A”,“B” 但没有购买产品 “C” 的客户的 customer_id 和 customer_name,因为我们想推荐他们购买这样的产品。
返回按 customer_id 排序 的结果表。
返回结果格式如下所示。
示例 1:
输入:
Customers 表:
customer_id | customer_name |
---|---|
1 | Daniel |
2 | Diana |
3 | Elizabeth |
4 | Jhon |
Orders 表:
order_id | customer_id | product_name |
---|---|---|
10 | 1 | A |
20 | 1 | B |
30 | 1 | D |
40 | 1 | C |
50 | 2 | A |
60 | 3 | A |
70 | 3 | B |
80 | 3 | D |
90 | 4 | C |
输出:
customer_id | customer_name |
---|---|
3 | Elizabeth |
解释:
只有 customer_id 为 3 的顾客购买了产品 A 和产品 B ,却没有购买产品 C 。
SELECT DISTINCT a.customer_id, d.customer_name
FROM Orders a, Orders b, Orders c, Customers d
WHERE a.customer_id = b.customer_id
AND b.customer_id = c.customer_id
AND a.product_name = 'A'
AND b.product_name = 'B'
AND a.customer_id = d.customer_id
AND NOT EXISTS(SELECT * FROM Orders WHERE customer_id = c.customer_id AND product_name = 'C')
SELECT o.customer_id, customer_name
FROM orders o, customers c
WHERE o.customer_id = c.customer_id
GROUP BY o.customer_id
HAVING SUM(product_name = 'A') > 0 AND SUM(product_name = 'B') > 0 AND SUM(product_name = 'C') = 0
SELECT c.customer_id, customer_name
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id
HAVING SUM(product_name = 'A') AND SUM(product_name = 'B') AND NOT SUM(product_name = 'C')
从以上两种写法可以看出在 HAVING 中,
1、SUM(条件表达式) 如果是大于0,可以省略
SUM(product_name = 'A') > 0 AND SUM(product_name = 'B') > 0
→ SUM(product_name = 'A') AND SUM(product_name = 'B')
2、SUM(条件表达式) 如果是等于0,则在加前面加 NOT,后面可以省略
SUM(product_name = 'C') = 0
→ NOT SUM(product_name = 'C')