- 学习:知识的初次邂逅
- 复习:知识的温故知新
- 练习:知识的实践应用
目录
一,原题力扣链接
二,题干
销售表:
Sales
+-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ sale_id 是这个表的主键(具有唯一值的列)。 product_id 是 Product 表的外键(reference 列)。 该表的每一行显示产品product_id在某一年的销售情况。 请注意价格是每单位的。产品表:
Product
+--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | +--------------+---------+ product_id 是这个表的主键(具有唯一值的列)。 该表的每一行表示每种产品的产品名称。编写解决方案,统计每个产品的销售总量。
返回结果表 无顺序要求 。
结果格式如下例子所示。
示例 1:
输入: Sales
表: +---------+------------+------+----------+-------+ | sale_id | product_id | year | quantity | price | +---------+------------+------+----------+-------+ | 1 | 100 | 2008 | 10 | 5000 | | 2 | 100 | 2009 | 12 | 5000 | | 7 | 200 | 2011 | 15 | 9000 | +---------+------------+------+----------+-------+ Product 表: +------------+--------------+ | product_id | product_name | +------------+--------------+ | 100 | Nokia | | 200 | Apple | | 300 | Samsung | +------------+--------------+ 输出: +--------------+----------------+ | product_id | total_quantity | +--------------+----------------+ | 100 | 22 | | 200 | 15 | +--------------+----------------+
三,建表语句
Create table If Not Exists Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table If Not Exists Product (product_id int, product_name varchar(10));
Truncate table Sales;;
insert into Sales (sale_id, product_id, year, quantity, price) values ('1', '100', '2008', '10', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('2', '100', '2009', '12', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('7', '200', '2011', '15', '9000');
Truncate table Product;
insert into Product (product_id, product_name) values ('100', 'Nokia');
insert into Product (product_id, product_name) values ('200', 'Apple');
insert into Product (product_id, product_name) values ('300', 'Samsung');
四,分析
简简单单的 2表合并 然后分组聚合的题
select p.product_id
,sum(quantity) as total_quantity
from product p join sales s on p.product_id=s.product_id
group by p.product_id;
五,SQL解答
select p.product_id
,sum(quantity) as total_quantity
from product p join sales s on p.product_id=s.product_id
group by p.product_id;
六,验证
七,知识点总结
- 内连接的运用
- 分组聚合的运用
- 别名的运用