[我正在尝试仅将类别中排名前三的销售产品(按类别中的交易(id)count(id)
中的发生率仅排名前三的产品)。我在寻找很多可能的解决方案,但没有结果。似乎在MySQL中有点棘手,因为不能简单地使用top()函数等等。下面的示例数据结构:
+--------+------------+-----------+
| id |category_id | product_id|
+--------+------------+-----------+
| 1 | 10 | 32 |
| 2 | 10 | 34 |
| 3 | 10 | 32 |
| 4 | 10 | 21 |
| 5 | 10 | 100 |
| 6 | 7 | 101 |
| 7 | 7 | 39 |
| 8 | 7 | 41 |
| 9 | 7 | 39 |
+--------+------------+-----------+
如果您正在运行MySQL 8.0,则可以为此使用窗口函数rank()
:
select *
from (
select
category_id,
product_id,
count(*) cnt,
rank() over(partition by category_id order by count(*) desc) rn
from mytable
group by category_id, product_id
) t
where rn <= 3