MySQL:Top K,带有重复项

时间:2015-10-28 05:46:20

标签: mysql

Ex:假设我有10个类别(a,b,c,d,e,f,g,h,i,j),每个类别的产品数量为:(5,6,10,4) ,10,4,6,10,10,4)。现在,如果我想找到最大产品的前5个类别:

c - 10
e - 10
h - 10
i - 10
(b,g) - 6 (sometimes it will be b and sometimes it will be g, if I use the LIMIT 5 option.)

我需要的:如果有类别相同的类别并且没有固定的规则来返回哪个类别,那么我希望sql查询返回所有这些类别。在上面的例子中,我希望sql查询返回6行。如果所有类别都有10个产品,然后查询前5个,我需要返回10行。

我看到了这个问题:Selecting the top 5 in a column with duplicates。但它有不同的要求。

1 个答案:

答案 0 :(得分:2)

您可以通过内部选择来实现此目的。首先获得前k个类别的计数,然后获得具有这些计数的所有类别。

Select cat_count, category from 
    (select count(category) as top_count
    from products group by category order by count(category) desc limit 5)
as t1 inner join 
    (select count(category) as cat_count, category 
    from products group by category) as t2 on t1.top_count = t2.cat_count

或者说不同:

select count(category), category 
from products 
group by category
having count(category) in 
    (select count(category) as top_count
    from products 
    group by category
    order by count(category) desc limit 5)