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

统计每个产品的销售情况

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

# customers customer_id
# products product_id
# orders order_id

#1.product_id
#2.product_id
#3.product_id
#4.product_id
#5.product_id
#6.product_id+month
#7.product_id+age_group


with t1 as(
    select
    p.product_id
    ,unit_price
    ,sum(quantity) as total_quantity
    ,sum(quantity)*unit_price as total_sales
    ,sum(quantity)*unit_price/12 as avg_monthly_sales
    from products p
    left join orders o
    on p.product_id = o.product_id
    where year(order_date) = 2023
    group by 1,2) #前5需求表
,t2 as(
    select
    product_id
    ,max(monthly_sales) as monthly_sales
    from
        (select
        p.product_id
        ,month(order_date) as month
        ,sum(quantity)as monthly_sales
        from products p
        left join orders o
        on p.product_id = o.product_id
        where year(order_date) = 2023
        group by 1,2)a
    group by 1) #第6需求表
,t3 as(
    select
    product_id
    ,age_group
    from
        (select
        product_id
        ,age_group
        ,age_group_quantity
        ,row_number()over(partition by product_id order by age_group_quantity desc,age_group) as rn
        from
            (select
            p.product_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'
            else '61+' end  as age_group
            ,sum(quantity) as age_group_quantity
            from products p
            left join orders o
            on p.product_id = o.product_id
            left join customers c
            on o.customer_id = c.customer_id
            where year(order_date) = 2023
            group by 1,2,3)a)b
        where rn = 1) #第7需求表

select 
t1.product_id
,t1.total_sales
,t1.unit_price
,t1.total_quantity
,round(t1.avg_monthly_sales,2) as avg_monthly_sales
,round(t2.monthly_sales,2) as max_monthly_quantity
,t3.age_group as customer_age_group
from t1
left join t2
on t1.product_id = t2.product_id
left join t3
on t1.product_id = t3.product_id
order by total_sales desc,customer_age_group;



















全部评论

相关推荐

03-14 16:04
已编辑
安徽农业大学 算法工程师
痴心的她allin秋...:啥笔试都挂怎么办,某9本考研下岸,练也没时间了,对算法也不感兴趣,大部分大厂笔试只能A0-1个😄
米哈游笔试
点赞 评论 收藏
分享
03-03 23:42
复旦大学 Java
tongx_:闹呢,这找不到其他人还活不活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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