题解 | 查询出不同类别商品中,销售金额排名前三且利润率超过 20%的商品信息

查询出不同类别商品中,销售金额排名前三且利润率超过 20%的商品信息

https://www.nowcoder.com/practice/3d70132f4c14442cada25fec0198e743

WITH
t1 AS (     -- 清洗数据,关联两表,得出包含所需数据的底表 
SELECT
    sp.product_id,
    sp.product_name,
    sp.category_id,
    SUM(ll.sales_amount) AS total_sales_amount,
    SUM(ll.cost_amount) AS total_cost_amount
FROM product_category AS sp
LEFT JOIN sales_and_profit AS ll
    ON sp.product_id = ll.product_id
GROUP BY sp.product_id,sp.product_name,sp.category_id
),

t2 AS (     -- 计算利润率
SELECT
    product_id,
    product_name,
    category_id,
    total_sales_amount,
    COALESCE(ROUND((total_sales_amount - total_cost_amount) / NULLIF(total_sales_amount,0),2),0) AS profit_rate
FROM t1
),

t3 AS (     -- 计算每个商品类别的销售额排名
SELECT
    product_id,
    product_name,
    category_id,
    total_sales_amount,
    profit_rate,
    RANK() OVER(PARTITION BY category_id ORDER BY total_sales_amount DESC) AS rk
FROM t2
)

SELECT      -- 清洗已完成,按照题目要求输出数据
    product_id,
    product_name,
    category_id,
    total_sales_amount AS sales_amount,
    profit_rate
FROM t3
WHERE rk <= 3  AND profit_rate > 0.2
ORDER BY category_id ASC,total_sales_amount DESC,product_id ASC;

全部评论

相关推荐

专业嗎喽:个人信息名字太大,合到电话邮箱那一栏就行,有党员写过党,剩下其他全删,站空太大了 把实习经历丰富,放最前面,然后是个人评价,技能之类的,然后是学校信息。项目经历最后面,可以就选一个自己擅长的。 现在是学校不是92就扣分的,没必要放前面。 然后现在看重实习经历>竞赛经历(校园经历)>课程项目经历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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