随笔 - 384  文章 - 0  评论 - 0  阅读 - 13万

力扣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';

posted on   我不想一直当菜鸟  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2022-04-10 selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.的解决办法
2022-04-10 力扣442(java)-数组中重复的数据(中等)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示