返回col匹配计数的前2的行的所有行

时间:2017-01-29 15:14:48

标签: sql postgresql

我想计算列出productID的次数,然后使用它来返回productID与计算的前2位匹配的所有行。

所以拿这个表:

ID | productID
1  | 2 
2  | 2
3  | 3
4  | 3
5  | 4
6  | 2

查询将返回:

ID | productID
1  | 2
2  | 2
6  | 2
3  | 3
4  | 3

我不想使用LIMIT,因为我不知道将返回多少行,我需要全部抓取它们。

我想以一种方式编写查询,我可以使用偏移来抓住下一个前2(所以3-4,然后是5-6等)

我不完全确定单独使用SQL是可能的,我提出的最好的是:

SELECT ID, productID, COUNT(*)
FROM table
GROUP BY ID, productID

3 个答案:

答案 0 :(得分:3)

如果我理解正确:

select t.*
from t
where t.productId in (select t2.productId
                      from t t2
                      group by productId
                      order by count(*) desc
                      limit 2
                     )
order by t.productId;

如果要在查询中使用计数(比如说排序),那么在from子句中使用子查询("派生表")代替:

select t.*
from t join
     (select t2.productId, count(*) as cnt
      from t t2
      group by productId
      order by count(*) desc
      limit 2
     ) tt
     on t.productId = tt.productId
order by count(*) desc, id;

最后,如果你只想要前两个的id,那么将它们聚合成一个数组就足够了:

select t2.productId, array_agg(id) as ids
from t t2
group by productId
order by count(*) desc
limit 2;

这将返回:

productID    ids
    2        {1,2,6}
    3        {3,4}

答案 1 :(得分:1)

你可以找到每个productId的数量,并在其上找到密集的排名并过滤以根据计数获得前2名:

select
    id, productId
from (
    select
        t.*,
        dense_rank() over (order by cnt desc) rnk
    from (
        select
            t.*,
            count(*) over (partition by productId) cnt
        from your_table t
    ) t
) t where rnk <= 2
order by cnt desc, id;

答案 2 :(得分:0)

Select * From table t
where productId In
   (Select productId from table
    group by productId
    order by count<*> desc
    limit 2)