You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-- customer_id is the id of the customer who bought the product "product_name".
25
+
26
+
27
+
-- 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.
28
+
29
+
-- Return the result table ordered by customer_id.
30
+
31
+
-- The query result format is in the following example.
32
+
33
+
34
+
35
+
-- Customers table:
36
+
-- +-------------+---------------+
37
+
-- | customer_id | customer_name |
38
+
-- +-------------+---------------+
39
+
-- | 1 | Daniel |
40
+
-- | 2 | Diana |
41
+
-- | 3 | Elizabeth |
42
+
-- | 4 | Jhon |
43
+
-- +-------------+---------------+
44
+
45
+
-- Orders table:
46
+
-- +------------+--------------+---------------+
47
+
-- | order_id | customer_id | product_name |
48
+
-- +------------+--------------+---------------+
49
+
-- | 10 | 1 | A |
50
+
-- | 20 | 1 | B |
51
+
-- | 30 | 1 | D |
52
+
-- | 40 | 1 | C |
53
+
-- | 50 | 2 | A |
54
+
-- | 60 | 3 | A |
55
+
-- | 70 | 3 | B |
56
+
-- | 80 | 3 | D |
57
+
-- | 90 | 4 | C |
58
+
-- +------------+--------------+---------------+
59
+
60
+
-- Result table:
61
+
-- +-------------+---------------+
62
+
-- | customer_id | customer_name |
63
+
-- +-------------+---------------+
64
+
-- | 3 | Elizabeth |
65
+
-- +-------------+---------------+
66
+
-- Only the customer_id with id 3 bought the product A and B but not the product C.
67
+
68
+
-- Solution
69
+
with t1 as
70
+
(
71
+
select customer_id
72
+
from orders
73
+
where product_name ='B'and
74
+
customer_id in (select customer_id
75
+
from orders
76
+
where product_name ='A'))
77
+
78
+
Selectt1.customer_id, c.customer_name
79
+
from t1 join customers c
80
+
ont1.customer_id=c.customer_id
81
+
wheret1.customer_id!= all(select customer_id
82
+
from orders
83
+
where product_name ='C')
Collapse file: Medium/Managers with atleast 5 direct reports.sql
-- The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
3
+
4
+
-- +------+----------+-----------+----------+
5
+
-- |Id |Name |Department |ManagerId |
6
+
-- +------+----------+-----------+----------+
7
+
-- |101 |John |A |null |
8
+
-- |102 |Dan |A |101 |
9
+
-- |103 |James |A |101 |
10
+
-- |104 |Amy |A |101 |
11
+
-- |105 |Anne |A |101 |
12
+
-- |106 |Ron |B |101 |
13
+
-- +------+----------+-----------+----------+
14
+
-- Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:
0 commit comments