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

统计每个产品的销售情况

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

好抽象的题目...

with monthlysales as (
    select p.product_id, 
        date_format(o.order_date, '%y-%m') as month, 
        sum(o.quantity * p.unit_price) as monthly_sales,
        sum(o.quantity) as monthly_quantity
    from products p 
    join orders o on p.product_id = o.product_id
    where year(o.order_date) = 2023
    group by p.product_id, date_format(o.order_date, '%y-%m')
),
agegroup as (
    select product_id, age_group as customer_age_group
    from (
        select product_id, age_group,
            rank() over (partition by product_id order by sum(quantity) desc, age_group asc ) as rnk
        from (
            select o.product_id,
                case 
                    when c.customer_age <= 10 then '1-10'
                    when c.customer_age <= 20 then '11-20'
                    when c.customer_age <= 30 then '21-30'
                    when c.customer_age <= 40 then '31-40'
                    when c.customer_age <= 50 then '41-50'
                    when c.customer_age <= 60 then '51-60'
                    else '61+' 
                end as age_group, o.quantity
            from customers c 
            join orders o on c.customer_id = o.customer_id
            where year(o.order_date) = 2023
        ) t
        group by product_id, age_group
    ) ranked
    where rnk = 1
)
select 
    p.product_id,
    round(sum(m.monthly_sales), 2) as total_sales,
    round(p.unit_price, 2) as unit_price,
    sum(m.monthly_quantity) as total_quantity,
    round(sum(m.monthly_sales) / 12, 2) as avg_monthly_sales,
    max(m.monthly_quantity) as max_monthly_quantity,
    a.customer_age_group as customer_age_group
from products p
join monthlysales m on p.product_id = m.product_id
join agegroup a on p.product_id = a.product_id
group by p.product_id, p.unit_price, a.customer_age_group
order by total_sales desc, p.product_id asc;

全部评论

相关推荐

03-03 23:12
已编辑
北京邮电大学 Java
书海为家:我来给一点点小建议,因为毕竟还在学校不像工作几年的老鸟有丰富的项目经验,面试官在面试在校生的时候更关注咱们同学的做事逻辑和思路,所以最好在简历中描述下自己做过项目的完整过程,比如需求怎么来的,你对需求的解读,你想到的解决办法,遇到困难如何找人求助,最终项目做成了什么程度,你从中收获了哪些技能,你有什么感悟。
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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