2021-05-06

产品销售分析

需求一:获取产品表 Product 中所有的 产品名称 product name 以及 该产品在 Sales 表中相对应的 上市年份 year价格 price

展示效果:

product_nameyearprice
Nokia20085000
Nokia20095000
Apple20119000
Create table 43_Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table 43_Product (product_id int, product_name varchar(10));
Truncate table 43_Sales;
insert into 43_Sales (sale_id, product_id, year, quantity, price) values (1, 100, 2008, 10, 5000);
insert into 43_Sales (sale_id, product_id, year, quantity, price) values (2, 100, 2009, 12, 5000);
insert into 43_Sales (sale_id, product_id, year, quantity, price) values (7, 200, 2011, 15, 9000);
Truncate table 43_Sales;
insert into 43_Product (product_id, product_name) values (100, 'Nokia');
insert into 43_Product (product_id, product_name) values (200, 'Apple');
insert into 43_Product (product_id, product_name) values (300, 'Samsung');

最终SQL:

select
	t2.product_name,
	t1.year,
	t1.price
from
	43_Sales t1
join
	43_Product t2
on 
	t1.product_id = t2.product_id


需求二:按产品 id(product_id )来统计每个产品的销售总量。

展示效果:

product_idtotal_quantity
10022
20015

最终SQL:

SELECT
    product_id, 
    SUM(quantity) as total_quantity
FROM
    43_Sales
GROUP BY
    product_id;

需求三:选出每个销售产品的第一年 的 产品 id、年份、数量 和 价格。

展示效果:

product_idfirst_yearquantityprice
1002008105000
2002011159000

最终SQL:

select 
      product_id,
      year as first_year, 
      quantity,
      price
from 
      43_Sales
where 
     (product_id , year) in(
                            select
                                  product_id ,
                                  min(year)
                            from
                                  43_Sales
                            group by
                                  product_id
                            );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值