题目描述

(通过次数12,662 | 提交次数26,425,通过率47.92%)

销售表Sales:
+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| year        | int   |
| quantity    | int   |
| price       | int   |
+-------------+-------+
(sale_id, year) 是这张表的主键。
product_id 是产品表的外键。
这张表的每一行都表示:编号 product_id 的产品在某一年的销售额。
请注意,价格是按每单位计的。

产品表Product:
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
+--------------+---------+
product_id 是这张表的主键。
这张表的每一行都标识:每个产品的 id 和 产品名称。

编写一个 SQL 查询,选出每个销售产品第一年 销售的 产品 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  |
+------------+------------+----------+-------+

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/product-sales-analysis-iii
//测试数据
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));

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');

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');

解题思路

Sales表中保存了产品在每一年的销售情况。产品的起售年份可能不一样,一个产品也可能有多年都有持续销售。
题目要求,计算出产品开始销售的首年的销售数据。
也就是说,虽然Sales表中保存了产品多年的数据,但题目只要求获取每个产品上市销售第一年的数据。
那么,可以先计算出每个产品上市销售的第一年的年份,然后再以产品+第一年的年份过滤出对应的销售数据。
“每个产品上市销售的第一年的年份”:直接通过GROUP BY+MIN即可获取结果。然后再使用WHERE条件过滤。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。

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

picture loss