表: 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 。
思路:
1、选择字段
product_name 用于标识每个产品。
sum(unit) 用于统计每个产品在指定时间段内的销售数量。
2、表关联
主表 Products 与明细表 Orders 通过 product_id 进行左连接。
左连接可以保证即使某个产品在该时间段没有销售记录,也会显示在结果中,销售数量为零。
3、数据过滤
to_char(order_date, 'yyyy-mm') = '2020-02' 用于筛选 2020 年 2 月的订单数据。
注意,这里放在 where 中会排除没有订单的产品,如果希望保留所有产品,可考虑将过滤条件放到连接条件中。
4、分组聚合
按 product_name 分组,计算每个产品的总销量。
sum(unit) 对每组产品的销售数量进行求和。
5、结果筛选
使用 having sum(unit) >= 100 对聚合后的结果进行条件筛选,只保留销量大于等于 100 的产 品。
不能使用 where 直接对聚合函数进行筛选。
6、整体逻辑
先从 Products 表出发,通过左连接获取每个产品对应的订单信息。
对订单数据按产品分组,计算总销量。
最后筛选出销量超过阈值的产品,得到目标结果。
代码:
sql
select
product_name,
sum(unit) unit
from Products t1
left join Orders t2
on t1.product_id = t2.product_id
where to_char(order_date, 'yyyy-mm') = '2020-02'
group by product_name
having sum(unit) >= 100