38. A & B Buyers Without C
Your company wants to promote product C to customers who have already shown interest in related products A and B, but have not purchased C yet. These customers are potential buyers for C, and you'd like to target them for marketing campaigns.
You are given two tables:
Customers:
āāāāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā customer_id ā int ā āāāāāāāāāāāāāāāāā¼āāāāāāāāāāā ā customer_name ā varchar ā āāāāāāāāāāāāāāāāā©āāāāāāāāāāā
- customer_id is primary key above table(Customers).
- customer_name is the name of the customer.
Orders:
āāāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā order_id ā int ā āāāāāāāāāāāāāāāā¼āāāāāāāāāāā ā customer_id ā int ā āāāāāāāāāāāāāāāā¼āāāāāāāāāāā ā product_name ā varchar ā āāāāāāāāāāāāāāāā©āāāāāāāāāāā
- order_id is primary key above table(Orders)
- customer_id is a foreign key that references the Customers table.
- product_name is the name of the product.
Write an SQL query to return the customer_id and customer_name of customers who have:
- Purchased both 'A' and 'B',
- Not purchased 'C'.
Return the result ordered by customer_id.
Example 1:
Example:
Input:
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 ā āāāāāāāāāāāā©āāāāāāāāāāāāāā©āāāāāāāāāāāāāāā
Output:
āāāāāāāāāāāāāāā¦āāāāāāāāāāāāāāāā ā customer_id ā customer_name ā ā āāāāāāāāāāāāāā¬āāāāāāāāāāāāāāā⣠ā 3 ā Elizabeth ā āāāāāāāāāāāāāāā©āāāāāāāāāāāāāāāā
Explanation:Ā
Only the customer_id with id 3 bought the product A and B but not the product C.
- Customer 1 = A, B, C = No
- Customer 2 = Only A = No
- Customer 3 = A, B, D = Yes
- Customer 4 = Only C = No
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.