Leetcode1070. 产品销售分析 III(中等)

题目
销售表 Sales:

+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| year        | int   |
| quantity    | int   |
| price       | int   |
+-------------+-------+

sale_id 是此表的主键。
产品 ID 是产品表的外键。
请注意,价格是按每单位计的。

产品表 Product:

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
+--------------+---------+

产品 ID 是此表的主键。

编写一个 SQL 查询,选出每个销售产品的 第一年 的 产品 id、年份、数量 和 价格。

查询结果格式如下:
Sales table:

+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+ 
| 1       | 100        | 2008 | 10       | 5000  |
| 2       | 100        | 2009 | 12       | 5000  |
| 7       | 200        | 2011 | 15       | 9000  |
+---------+------------+------+----------+-------+

Product table:

+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100        | Nokia        |
| 200        | Apple        |
| 300        | Samsung      |
+------------+--------------+

Result table:

+------------+------------+----------+-------+
| product_id | first_year | quantity | price |
+------------+------------+----------+-------+ 
| 100        | 2008       | 10       | 5000  |
| 200        | 2011       | 15       | 9000  |
+------------+------------+----------+-------+

解答
这种类型的好像做过好多遍了
先选择每个id对应的最小年份

select product_id, MIN(year)
from Sales
group by product_id

然后与Sales表进行连接 选出所需结果

select tmp.product_id, tmp.min_year as first_year, S.quantity, S.price
from Sales as S
join (select product_id, MIN(year) as min_year 
from Sales
group by product_id) as tmp
on S.product_id = tmp.product_id and S.year = tmp.year

用二元in也可以

select S.product_id, S.min_year as first_year, S.quantity, S.price
from Sales as S
where (S.product_id, S.year) in (
select product_id, MIN(year)
from Sales
group by product_id);

你可能感兴趣的:(Leetcode1070. 产品销售分析 III(中等))