Description
Table: Product
| Column Name | Type |
|---|---|
| product_id | int |
| product_name | varchar |
| unit_price | int |
product_idis the primary key (column with unique values) of this table.- Each row of this table indicates the name and the price of each product.
Table: Sales
| Column Name | Type |
|---|---|
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | date |
| quantity | int |
| price | int |
- This table might have repeated rows.
product_idis a foreign key (reference column) to theProducttable.buyer_idis never NULL.sale_dateis never NULL.- Each row of this table contains some information about one sale.
Problem Statement
Write a solution to report the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products presented in the Product table.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Producttable:
| product_id | product_name | unit_price |
|---|---|---|
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
Salestable:
| seller_id | product_id | buyer_id | sale_date | quantity | price |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 1 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 3 | 2019-05-13 | 2 | 2800 |
Output:
| buyer_id |
|---|
| 1 |
Explanation:
- The buyer with id
1bought an ‘S8’ but did not buy an ‘iPhone’. The buyer with id3bought both.
Solution
Here, you want to find buyers who have not bought an iPhone. In order to find information on the product, you first need to join Product and Sales table. You can assign this to a temporary view.
1WITH product_sales AS (
2 SELECT p.product_id, p.product_name, s.buyer_id
3 FROM Product p
4 JOIN Sales s
5 ON p.product_id = s.product_id
6) SELECT * FROM product_sales;
Next, you need to filter the buyers who have bought an iPhone. How do you find the buyers who have ever bought iPhone?
1SELECT buyer_id
2 FROM product_sales
3 WHERE product_name = 'iPhone';
Next, you need to find the buyers who have bought S8, but not iPhone. Notice that this is exclusive-OR relationship. If the user has bought both models, they should not be included in the output. You can achieve this using WHERE clause.
1SELECT DISTINCt buyer_id
2 FROM product_sales
3 WHERE product_name = 'S8'
4 AND buyer_id NOT IN (
5 SELECT buyer_id
6 FROM product_sales
7 WHERE product_name = 'iPhone'
8 );
The complete solution looks like this.
1WITH product_sales AS (
2 SELECT p.product_id, p.product_name, s.buyer_id
3 FROM Product p
4 JOIN Sales s ON p.product_id = s.product_id
5) SELECT DISTINCT buyer_id
6 FROM product_sales
7 WHERE product_name = 'S8' AND buyer_id NOT IN (
8 SELECT buyer_id
9 FROM product_sales
10 WHERE product_name = 'iPhone'
11 );


Comments