跳到主要内容

1070.产品销售分析 III

序号题目难度
1070题目链接中等

题目大意大意​

编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。

对每个 product_id,找到其在Sales表中首次出现的最早年份。 返回该产品在该年度的 所有 销售条目。 返回一张有这些列的表:product_id,first_year,quantity 和 price。

结果表中的条目可以按 任意顺序 排列。

销售表 Sales:

Column NameType
sale_idint
product_idint
yearint
quantityint
priceint

(sale_id, year) 是这张表的主键(具有唯一值的列的组合)。 product_id 是产品表的外键(reference 列)。 这张表的每一行都表示:编号 product_id 的产品在某一年的销售额。 一个产品可能在同一年内有多个销售条目。 请注意,价格是按每单位计的。

示例​

输入​

Sales 表:

sale_idproduct_idyearquantityprice
11002008105000
21002009125000
72002011159000

输出​

product_idfirst_yearquantityprice
1002008105000
2002011159000

参考答案​

with t1 as (
select
product_id
,min(year) first_year
from Sales
group by 1
)
select
t0.product_id
,t1.first_year
,t0.quantity
,t0.price
from Sales t0
join t1
on t0.product_id = t1.product_id
and t0.year = t1.first_year
;