Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

41 产品销售分析 III #50

Open
astak16 opened this issue Feb 9, 2022 · 0 comments
Open

41 产品销售分析 III #50

astak16 opened this issue Feb 9, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Feb 9, 2022

题目

编写一个 SQL 查询,选出每个销售产品的 第一年 的 product_idfirst_yearquantity ****和 price

  • sales 表中的主键是 sale_id 外键是 product_id
  • product 表中的主键是 product_id

ps:如果第一年有两个价格也需要查询出来

CREATE TABLE sales (
	sale_id INT,
	product_id INT,
	year INT,
	quantity INT,
	price INT 
);
INSERT INTO sales ( sale_id, product_id, year, quantity, price ) VALUES
( 1, 100, 2008, 10, 5000 ),
( 2, 100, 2009, 12, 5000 ),
( 7, 200, 2011, 15, 9000 );
	
CREATE TABLE product ( 
	product_id INT, 
	product_name VARCHAR ( 10 ) 
);
INSERT INTO product ( product_id, product_name ) VALUES
( 100, 'Nokia' ),
( 200, 'Apple' ),
( 300, 'Samsung' );

分析

  1. 需要先知道第一年 first_year 和产品id product_id
  2. product 表用不到

SQL:方法一

select
	product_id,
	year as first_year,
	quantity,
	price
from (
	select 
		product_id,
		year,
		quantity,
		price,
		rank() over(partition by product_id order by year) as rn
	from sales
) as temp where rn = 1;

解析

  1. 使用窗口函数 rank(),按照 product_id 分组, year 升序排序,得到 rn
    1. 如果第一年有多个价格,都需要查询出来,所以这里不能使用 row_number
  2. 将第一步查询出来的表作为临时表 temp
  3. 查询临时表 temp 筛选出 rn = 1 的数据,因为 rn 是升序排序的,所以 rn = 1 就是第一年

SQL:方法二

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

解析

  1. 使用 group by 按照 product_id 进行分组,查询出 product_id 和第一年 first_year
  2. 查询 sales 表,筛选出第一步中查询出来的 product_idfirst_year

SQL:方法三

select
	sales.product_id,
	first_year,
	quantity,
	price
from (
	select product_id, min(year) first_year from sales group by product_id
) as temp 
left join sales on temp.product_id = sales.product_id 
and temp.first_year = sales.year;

解析

  1. 使用 group by 按照 product_id 进行分组,查询出 product_id 和第一年 first_year
  2. 将第一步作为临时表 tempsales 左连,连接条件是 product_idfirst_year = year
@astak16 astak16 added the 中等 label Feb 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant