-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode Question - 1398.sql
49 lines (37 loc) · 1.33 KB
/
Leetcode Question - 1398.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
--Customers Who Bought Products A and B but Not C.
--Table: Customers
+---------------------+---------+
| Column Name | Type |
+---------------------+---------+
| customer_id | int |
| customer_name | varchar |
+---------------------+---------+
--customer_id is the column with unique values for this table.
--customer_name is the name of the customer.
--Table: Orders
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| order_id | int |
| customer_id | int |
| product_name | varchar |
+---------------+---------+
--order_id is the column with unique values for this table.
--customer_id is the id of the customer who bought the product "product_name".
--Write a solution to report the customer_id and customer_name of customers who bought products "A", "B" but did not buy the product "C" since we want to recommend them to purchase this product.
--Return the result table ordered by customer_id.
--Solving with Subquery in SQL
SELECT c.customer_id, c.customer_name
FROM customers c
WHERE c.customer_id IN (
SELECT o.customer_id
FROM orders o
WHERE o.product_name IN ('A', 'B')
GROUP BY o.customer_id
HAVING COUNT(DISTINCT o.product_name) = 2
)
AND c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
WHERE o.product_name = 'C'
);