Skip to content

40 产品销售分析 II #49

Open
Open
@astak16

Description

@astak16

题目

编写一个 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions