我有10k-1m的商品,由字段product_id
,name
,category
,price
来描述。从每个类别中获取10个最昂贵商品的最快方法是什么?以前我检查过此答案https://stackoverflow.com/a/176985/9513268。我的桌子:
-------------------------------------
|product_id| name | category| price |
-------------------------------------
| 1 |Phone | Gadgets | 599.99|
------------------------------------
| 2 |Jacket| Clothes | 399.00|
-------------------------------------
| ... | ... | ... | ... |
-------------------------------------
您可以使用窗口功能,如链接的答案所示。
select *
from (
select t.*, rank() over(partition by category order by price desc) rn
from mytable t
) t
where rn <= 10
order by category, rn
关键是正确定义窗口函数的over()
子句。您希望category
排在前10位,因此此列将移至partition by
。您想要最昂贵的商品,因此order by
条件是price
降序。
您可以分别运行子查询并凝视rn
列,以更好地理解逻辑。