测试数据
drop table if exists Sales;
drop table if exists Product;
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');
答案:
select p.product_name,A.product_id,A.year,A.quantity,A.price
from (select product_id,
year,
quantity,
price,
row_number() over (partition by product_id order by year) fn
from sales) A
join product p on A.product_id=p.product_id
where fn = 1;