力扣1083(MySQL)-销售分析Ⅲ(简单)
题目:
Table: Product
Table: Sales
编写一个SQL查询,报告2019年春季才售出的产品。即仅在2019-01-01至2019-03-31(含)之间出售的商品。
以 任意顺序 返回结果表。
查询结果格式如下所示。
示例1:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sales-analysis-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
建表语句:
1 DROP table if exists Product_1084, Sales_1084; 2 Create table If Not Exists Product_1084 (product_id int, product_name varchar(10), unit_price int); 3 Create table If Not Exists Sales_1084 (seller_id int, product_id int, buyer_id int, sale_date date, quantity int, price int); 4 Truncate table Product_1084; 5 insert into Product_1084 (product_id, product_name, unit_price) values ('1', 'S8', '1000'),('2', 'G4', '800'),('3', 'iPhone', '1400'); 6 Truncate table Sales_1084; 7 insert into Sales_1084 (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('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');
解题思路:
方法一:
将两个表联结,并以 product_id和product_name进行分组,如果在分组的基础上 在2019-01-01至2019-03-31之间出售数等于产品数,那么该产品就只在春季出售过。
1 select b.product_id,product_name 2 from product_1084 a 3 join sales_1084 b 4 on a.product_id = b.product_id 5 group by b.product_id,product_name 6 having sum(sale_date between '2019-01-01' and '2019-03-31') = count(*);
方法二:使用聚合函数max()和min()
将两个表联结,并以 product_id和product_name进行分组,然后在分组的基础上筛选出 当前产品的最小日期大于等于2019-01-01 且 最大日期小于等于2019-03-31,那么该产品就只在春季出售过。
1 select b.product_id,product_name 2 from product_1084 a 3 join sales_1084 b 4 on a.product_id = b.product_id 5 group by b.product_id,product_name 6 having min(sale_date) >= '2019-01-01' and max(sale_date) <= '2019-03-31';