[SQL18] Write a SQL query to select the product ID, year, quantity and price of each product sold in the first year

Write a SQL query to select the product ID, year, quantity, and price of each product sold in the first year

The query result format is as follows: sales_table

sale_id     product_id      year        quantity      price
1           100             2008        10            5000
2           100             2009        12            5000
7           200             2011        15            9000
9           300             2009        14            6000
11          300             2011        18            6500

product_table

product_id     product_name
100            Nokia
200            Apple
300            Samsung

The following results are returned:

product_id    first_year        quantity       price
100           2008              10             5000
200           2011              15             9000
300           2009              14             6000

solve:

select a.product_id
      ,a.first_year
      ,a.quantity
      ,a.price
  from (
        select a.product_id
              ,a.year                                                           as first_year
              ,a.quantity
              ,a.price
              ,row_number() over(partition by a.product_id order by year)       as rn       ---根据product_id进行分组并按照year进行排序
          from sales_table a
          left join product_table b
            on a.product_id = b.product_id
        )a
 where rn = 1
;

结果:
product_id  first_year  quantity    price
100         2008         10         5000
200         2011         15         9000
300         2009         14         6000


备注:建表和数据
create table sales_table(sale_id int,product_id int,year int,quantity int,price int);
create table product_table(product_id int,product_name varchar(30));

insert into sales_table values(1,100,2008,10,5000);
insert into sales_table values(2,100,2009,12,5000);
insert into sales_table values(7,200,2011,15,9000);
insert into sales_table values(9,300,2009,14,6000);
insert into sales_table values(11,300,2011,18,6500);

insert into product_table values(100,'Nokia');
insert into product_table values(200,'Apple');
insert into product_table values(300,'Samsung');

 

Guess you like

Origin blog.csdn.net/debimeng/article/details/104123757