SELECT
product_name, -- 选择产品名称
total_sales, -- 选择总销量
-- 使用窗口函数对每个类别内的产品按销量和产品ID进行排名
ROW_NUMBER() OVER (PARTITION BY category ORDER BY total_sales DESC, product_id ASC) AS category_rank
FROM (
SELECT
MAX(category) AS category, -- 获取每个产品的类别
p.name AS product_name, -- 获取产品名称
SUM(quantity) AS total_sales, -- 计算总销量
p.product_id -- 获取产品的ID
FROM
products p
-- 将products表与orders表内连接,基于product_id
INNER JOIN orders o ON p.product_id = o.product_id
-- 按产品名称和产品ID进行分组
GROUP BY
p.name, p.product_id
) a

京公网安备 11010502036488号