-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path72.sql
83 lines (68 loc) · 2.54 KB
/
72.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
-- Question 72
-- Table: Customers
-- +---------------------+---------+
-- | Column Name | Type |
-- +---------------------+---------+
-- | customer_id | int |
-- | customer_name | varchar |
-- +---------------------+---------+
-- customer_id is the primary key 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 primary key for this table.
-- customer_id is the id of the customer who bought the product "product_name".
-- Write an SQL query 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 buy this product.
-- Return the result table ordered by customer_id.
-- The query result format is in the following example.
-- Customers table:
-- +-------------+---------------+
-- | customer_id | customer_name |
-- +-------------+---------------+
-- | 1 | Daniel |
-- | 2 | Diana |
-- | 3 | Elizabeth |
-- | 4 | Jhon |
-- +-------------+---------------+
-- Orders table:
-- +------------+--------------+---------------+
-- | 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 |
-- +------------+--------------+---------------+
-- Result table:
-- +-------------+---------------+
-- | customer_id | customer_name |
-- +-------------+---------------+
-- | 3 | Elizabeth |
-- +-------------+---------------+
-- Only the customer_id with id 3 bought the product A and B but not the product C.
-- Solution
with t1 as
(
select customer_id
from orders
where product_name = 'B' and
customer_id in (select customer_id
from orders
where product_name = 'A'))
Select t1.customer_id, c.customer_name
from t1 join customers c
on t1.customer_id = c.customer_id
where t1.customer_id != all(select customer_id
from orders
where product_name = 'C')