欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > SQL-leetcode—1327. 列出指定时间段内所有的下单产品

SQL-leetcode—1327. 列出指定时间段内所有的下单产品

2025/2/10 12:28:56 来源:https://blog.csdn.net/MrZhangBaby/article/details/145500633  浏览:    关键词:SQL-leetcode—1327. 列出指定时间段内所有的下单产品

1327. 列出指定时间段内所有的下单产品

表: Products

±-----------------±--------+
| Column Name | Type |
±-----------------±--------+
| product_id | int |
| product_name | varchar |
| product_category | varchar |
±-----------------±--------+
product_id 是该表主键(具有唯一值的列)。
该表包含该公司产品的数据。

表: Orders

±--------------±--------+
| Column Name | Type |
±--------------±--------+
| product_id | int |
| order_date | date |
| unit | int |
±--------------±--------+
该表可能包含重复行。
product_id 是表单 Products 的外键(reference 列)。
unit 是在日期 order_date 内下单产品的数目。

写一个解决方案,要求获取在 2020 年 2 月份下单的数量不少于 100 的产品的名字和数目。

返回结果表单的 顺序无要求 。

查询结果的格式如下。

示例 1:

输入:
Products 表:
±------------±----------------------±-----------------+
| product_id | product_name | product_category |
±------------±----------------------±-----------------+
| 1 | Leetcode Solutions | Book |
| 2 | Jewels of Stringology | Book |
| 3 | HP | Laptop |
| 4 | Lenovo | Laptop |
| 5 | Leetcode Kit | T-shirt |
±------------±----------------------±-----------------+
Orders 表:
±-------------±-------------±---------+
| product_id | order_date | unit |
±-------------±-------------±---------+
| 1 | 2020-02-05 | 60 |
| 1 | 2020-02-10 | 70 |
| 2 | 2020-01-18 | 30 |
| 2 | 2020-02-11 | 80 |
| 3 | 2020-02-17 | 2 |
| 3 | 2020-02-24 | 3 |
| 4 | 2020-03-01 | 20 |
| 4 | 2020-03-04 | 30 |
| 4 | 2020-03-04 | 60 |
| 5 | 2020-02-25 | 50 |
| 5 | 2020-02-27 | 50 |
| 5 | 2020-03-01 | 50 |
±-------------±-------------±---------+
输出:
±-------------------±--------+
| product_name | unit |
±-------------------±--------+
| Leetcode Solutions | 130 |
| Leetcode Kit | 100 |
±-------------------±--------+
解释:
2020 年 2 月份下单 product_id = 1 的产品的数目总和为 (60 + 70) = 130 。
2020 年 2 月份下单 product_id = 2 的产品的数目总和为 80 。
2020 年 2 月份下单 product_id = 3 的产品的数目总和为 (2 + 3) = 5 。
2020 年 2 月份 product_id = 4 的产品并没有下单。
2020 年 2 月份下单 product_id = 5 的产品的数目总和为 (50 + 50) = 100 。

题解

要求获取在 2020 年 2 月份下单的数量不少于 100 的产品的名字和数目。

  • 获取在 2020 年 2 月份下单的 ——where 筛选时间
  • 数量不少于 100 —— 聚合后筛选

方法一 join+group by

with tmp as (
selectproduct_id,sum(unit) sum_unit
from Orders where date_format(order_date,'%Y-%m') = '2020-02'
group by product_id
)
select p1.product_name,o1.sum_unit as unit
from products p1 join tmp o1 on p1.product_id=o1.product_id
where o1.sum_unit >=100

方法二 join+group by + having

with tmp as (
selectproduct_id,sum(unit) sum_unit
from Orders where date_format(order_date,'%Y-%m') = '2020-02'
group by product_id
having sum_unit>=100
)
select p1.product_name,o1.sum_unit as unit
from products p1 join tmp o1 on p1.product_id=o1.product_id

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com