- 学习:知识的初次邂逅
- 复习:知识的温故知新
- 练习:知识的实践应用
目录
一,原题力扣链接
二,题干
销售表
Sales
:+-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ (sale_id, year) 是这张表的主键(具有唯一值的列的组合)。 product_id 是产品表的外键(reference 列)。 这张表的每一行都表示:编号 product_id 的产品在某一年的销售额。 请注意,价格是按每单位计的。产品表
Product
:+--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | +--------------+---------+ product_id 是这张表的主键(具有唯一值的列)。 这张表的每一行都标识:每个产品的 id 和 产品名称。编写解决方案,选出每个售出过的产品 第一年 销售的 产品 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 | first_year | quantity | price | +------------+------------+----------+-------+ | 100 | 2008 | 10 | 5000 | | 200 | 2011 | 15 | 9000 | +------------+------------+----------+-------+
三,建表语句
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');s
四,分析
第一步,rank开窗 以产品id分组,以年排序 生成一个序列
第二步,取第一
第三步,映射对应的列,改名,输出
这是一道简简单单的 分组求top1的题
第一步,rank开窗 以产品id分组,以年排序 生成一个序列
with t1 as (
select product_id,year,quantity,price,
rank() over (partition by product_id order by year) rn #允许并列
from sales
)
select * from t1;
第二步,取第一
第三步,映射对应的列,改名,输出
五,SQL解答
with t1 as (
select product_id,year,quantity,price,
rank() over (partition by product_id order by year) rn #允许并列
from sales
)
# select * from t1;
,t2 as (
select
product_id,year as first_year ,quantity,price
from t1 where rn=1
)
select * from t2;
六,验证
七,知识点总结
- 分组求top1 类型的题
- rank开窗考虑并列
- 条件过滤的运用
- 学习:知识的初次邂逅
- 复习:知识的温故知新
- 练习:知识的实践应用