1、题目描述
Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.
The query result format is in the following example:
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 | 2 | 3 | 2019-06-02 | 1 | 800 |
3 | 3 | 4 | 2019-05-13 | 2 | 2800 |
Result table:
product_id | product_name |
---|---|
1 | S8 |
The product with id 1 was only sold in spring 2019 while the other two were sold after.
来源:力扣(LeetCode)
2、解题思路
更上一题差不多的思路
1# 首先,增加子表,查询所有不在'2019-01-01' and '2019-03-31'
之间销售的product_id
select p.product_id
from Product p right join Sales s
on s.product_id=p.product_id
where sale_date not between '2019-01-01' and '2019-03-31'
2# 然后,两表联查,条件是日期在'2019-01-01' and '2019-03-31'
之间,并且不在上述范围
3、提交记录
select distinct p.product_id,product_name
from Product p right join Sales s
on s.product_id=p.product_id
where sale_date between '2019-01-01' and '2019-03-31'
and p.product_id not in (
select p.product_id
from Product p right join Sales s
on s.product_id=p.product_id
where sale_date not between '2019-01-01' and '2019-03-31')