题解 | 哪些产品在特定时间段内表现最为出色

哪些产品在特定时间段内表现最为出色

https://www.nowcoder.com/practice/866a4614615b43a29750537ede4bf0c8

-- 逻辑拆解:找到2024年销量最高的产品(选好驱动的左表为products表,因为销售记录表很明显记录不唯一,会产生笛卡尔积)
-- 首先先把排名求出来,再取第一名即可,这里的可以挖的陷阱是GROUP BY 分组后,partition by 必须是group by的列或者是更小颗粒度
With sales_ranked AS(
SELECT
    t1.product_id,
    SUM(t2.sales_quantity) total_sales_quantity,
    SUM(t2.sales_amount) total_sales_amount,
    DENSE_RANK() OVER(ORDER BY SUM(t2.sales_quantity) DESC) ranking
FROM products t1
LEFT JOIN sales_records t2
ON t1.product_id = t2.product_id
AND t2.sales_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY t1.product_id
)
SELECT
    t1.product_id,
    t2.product_name,
    t1.total_sales_amount,
    t1.total_sales_quantity
FROM sales_ranked t1
LEFT JOIN products t2
ON t1.product_id = t2.product_id
WHERE t1.ranking = 1
ORDER BY t1.product_id


全部评论

相关推荐

03-23 15:00
已编辑
厦门大学 Java
xiaowl:你这个简历的问题是对于技术点、项目的描述,都是描述action的,对于面试官而言,仅能知道你干了什么,无法判断你为什么这么干,干的好不好。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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