SQL-leetcode—1070. 产品销售分析 III

1070. 产品销售分析 III

销售表 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 |
±-----------±-----------±---------±------+

题解

选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。

  • 也就是说根据join 的结果保留第一年的就行了

方法一 rank

with s1 as (
select product_id,year,quantity,price,
rank() over(partition by product_id order by year) as rk
from Sales 
)
select 
    s1.product_id,s1.year as first_year,s1.quantity,s1.price
from s1 join Product p1 on s1.product_id=p1.product_id
where rk = 1

方法二 子查询+in

select product_id,year as first_year,quantity,price
from Sales where (product_id,year) in (select product_id,min(year) from Sales group by product_id)

就这样吧,其他的再看看吧

这里想要再说明一下,细细品味吧骚年

row_number、rank、dense_rank三者的区别,老是忘,在这里再记录一下。
row_number 是按顺序排的,遇到重复,结果不会重复,不管值是啥
rank 是按顺序排的,遇到重复,结果一致,但会跳过重复的个数
dense_rank 是按顺序排的,遇到重复,结果一致,但不会跳过重复的个数

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

差别来了

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掉进悬崖的狼

请博主喝杯奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值