select p.name as product_name,a.t as total_sales,row_number()over(partition by p.category order by a.t desc) as category_rank
from (
select product_id,sum(quantity) as t
from orders 
group by product_id) a inner join products p on a.product_id=p.product_id
order by p.category,a.t desc

很明显是要按照product_id分组后计算总数,然后会有几个product_id,在同一个category下, 然后用窗口函数 用category分组, 然后在同一组里,用product_id的总数大小排名来计数。

最后再整体排序一下。

不过 这里row_number,或许应该用dense_rank()

📊 RANK() vs DENSE_RANK() 区别:

RANK()

跳过后续排名

1, 2, 2, 4, 5

DENSE_RANK()

不跳过排名

1, 2, 2, 3, 4