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

40 产品销售分析 II #49

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

40 产品销售分析 II #49

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

Comments

@astak16
Copy link
Owner

astak16 commented Feb 8, 2022

题目

编写一个 SQL 查询,按产品 product_id 来统计每个产品的销售总量。

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

输出字段 product_idtotal_quantity

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

分析

sales 表中就有每个产品的销量 quantity ,而且输出的字段也都在 sales 表中,所以这里 product 表没有作用。

SQL:方法一

select 
	product_id,
  sum(quantity) total_quantity 
from sales group by product_id;

解析

  1. 使用 group byproduct_id 分组
  2. 使用聚合函数 sum() 计算 quantity

SQL:方法二

select 
	distinct product_id,
	sum(quantity) over(partition by product_id) total_product
from sales;

解析

  1. 这里使用窗口函数按照 product_id 进行分组
  2. 使用聚合函数 sum() 计算 quantity
@astak16 astak16 added the 简单 label Feb 8, 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