题解 | 统计每个产品的销售情况

统计每个产品的销售情况

https://www.nowcoder.com/practice/d431aa7bf72c4fd7b048ec639bc83ad2

with customer_age as(
    select customer_id,
    customer_age,
    case when customer_age between 1 and 10 then '1-10'
    when customer_age between 11 and 20 then '11-20'
    when customer_age between 21 and 30 then '21-30'
    when customer_age between 31 and 40 then '31-40'
    when customer_age between 41 and 50 then '41-50'
    when customer_age between 51 and 60 then '51-60'
    when customer_age >60 then '61+' end 
    as customer_age_group
    from customers),
    
    2023_orders as(
    select
    order_id,
    o.customer_id,
    c.customer_age,
    c.customer_age_group,
    o.product_id,
    quantity,
    p.unit_price,
    quantity*unit_price as sales,
    order_date
    from orders o
    inner join products p on o.product_id=p.product_id
    inner join customer_age c on c.customer_id=o.customer_id
    where year(order_date)=2023),

    monthly_sales as(
    select 
    product_id,month(order_date),
    sum(quantity) as monthly_quantity,
    row_number() over(partition by product_id order by sum(quantity) desc) as rn1
    from 2023_orders
    group by product_id,month(order_date)
    ),

    age_group as(
    select
    product_id,
    customer_id,
    customer_age,
    customer_age_group,
    sum(quantity) as age_quantity,
    row_number() over(partition by product_id order by sum(quantity) desc,customer_age) as rn2
    from 2023_orders
    group by product_id,customer_id,customer_age,customer_age_group
    ),

    total_sales as(
    select
    product_id,
    round(sum(sales),2) as total_sales,
    round(unit_price,2) as unit_price,
    sum(quantity) as total_quantity,
    round(sum(sales)/12,2) as avg_monthly_sales
    from 2023_orders
    group by product_id
    )


select
total_sales.product_id,total_sales,unit_price,total_quantity,avg_monthly_sales,monthly_quantity as max_monthly_quantity,customer_age_group
from total_sales
inner join monthly_sales on total_sales.product_id=monthly_sales.product_id and rn1=1
inner join age_group on age_group.product_id=total_sales.product_id and rn2=1
order by total_sales desc,total_sales.product_id;

全部评论
点赞 回复 分享
发布于 05-04 09:51 江西

相关推荐

05-23 19:33
重庆大学 Java
只学了传统后端,马上去后端实习了,在想要不要学习agent开发相关的。27秋招和26相比难度如何?
我连备胎都不是却还在...:就暑期实习而言,大厂官宣hc 比 26 多,但是我观察看应该低于 26 的,估计秋招也不简单
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务