SELECT product_name, total_sales, ROW_NUMBER() OVER (PARTITION BY category ORDER BY total_sales DESC ) AS category_rank
FROM (SELECT name AS product_name, o.product_id, category, SUM(quantity) AS total_sales
      FROM orders o
               JOIN products p ON o.product_id = p.product_id
      GROUP BY o.product_id, category, name
      ORDER BY category, total_sales DESC, product_id) t;