我只想得到分类中的前3位销售产品(按事务(id) count(id)按每个类别排列的前3种产品)。我在寻找很多可能的解决方案,但没有结果。在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 |
+--------+------------+-----------+发布于 2020-02-19 11:47:52
在早期版本的MySQL中,我建议使用变量:
select cp.*
from (select cp.*,
(@rn := if(@c = category_id, @rn + 1,
if(@c := category_id, 1, 1)
)
) as rn
from (select category_id, product_id, count(*) as cnt
from mytable
group by category_id, product_id
order by category_id, count(*) desc
) cp cross join
(select @c := -1, @rn := 0) params
) cp
where rn <= 3;发布于 2020-02-19 11:09:18
如果您运行的是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在早期版本中,有一个选项是使用相关子查询进行筛选:
select
category_id,
product_id,
count(*) cnt
from mytable t
group by category_id, product_id
having count(*) >= (
select count(*)
from mytable t1
where t1.category_id = t.category_id and t1.product_id = t.product_id
order by count(*) desc
limit 3, 1
)https://stackoverflow.com/questions/60298969
复制相似问题