leetcode1083. Sales Analysis II (SQL)

Table: Product

+ --------- + -------------- +
| Column the Name | Type |
+ -------------- + - + -------
| product_id | int |
| PRODUCT_NAME | VARCHAR |
| unit_price | int |
+ -------------- + --------- +
product_id this is the table's primary key
table: Sales

+ ------------- + --------- +
| Column the Name | Type |
+ ------------- + ---- + -----
| seller_id | int |
| product_id | int |
| buyer_id | int |
| sale_date | DATE |
| the Quantity | int |
|. price | int |
+ ------ + ------ --------- +
this table does not have a primary key, it can have duplicate rows.
product_id is a foreign key for the Product table.
write a SQL query, purchased S8 cell phone but did not buy iPhone buyers. Note that S8 and the iPhone is the Product table products.

Shows the format of the query results, said:

Product table:
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1          | S8           | 1000       |
| 2          | G4           | 800        |
| 3          | iPhone       | 1400       |
+------------+--------------+------------+

Sales table:
+-----------+------------+----------+------------+----------+-------+
| 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  |
+-----------+------------+----------+------------+----------+-------+

The Table the Result:
+ ------------- +
| buyer_id |
+ ------------- +
| 1 |
+ ---------- + ---
id buyers purchased a 1 S8, but did not buy iPhone, and id 3 has at the same time buyers purchased the two phones.

Ideas: Isolated two phone id, find out bought two mobile phones based on the phone id list to determine each individual in the first list, and did not love the second list.

select distinct buyer_id
from Sales
where buyer_id in (select buyer_id from Sales where product_id=(select product_id from Product where product_name='S8')) 
and buyer_id not in (select buyer_id from Sales where product_id=(select product_id from Product where product_name='iPhone'));

 

Published 611 original articles · won praise 10000 + · views 1.43 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104437593