在Postgresql中分组限制10

时间:2012-05-30 19:40:44

标签: postgresql limit

我有一个问题:

select
    a.kli,
    b.term_desc,
    count(distinct(a.adic)) as count,
    a.partner_id

from
    ad_delivery.sgmt_kli_adic a
    join wand.wandterms b on a.kli = b.term_code
    join wand.wandterms c on b.term_desc=c.term_desc
    join dwh.sgmt_clients e on a.partner_id::varchar = e.partner_id
    join dwh.schema_names f on e.partner_id::integer = f.partner_id::integer
where
    a.partner_id::integer in (f.partner_id)
    and c.class_code = 969
group by a.partner_id, b.term_desc, a.kli
order by partner_id, count desc;

每个partner_id会返回某些字词的计数。我希望能够按照计数desc显示每个~40 partner_id的前10名

查询结果如

db=# SELECT * FROM xxx;
 pid | term_desc | count
----+------------+------
  4 | termdesc1  | 3434
  4 | termdesc2  | 235
  4 | termdesc3  | 367
  4 | termdesc4  | 4533
  5 | termdesc1  | 235
  5 | termdesc2  | 567
  5 | termdesc3  | 344
  5 | termdesc4  | 56
(10k+ rows)

1 个答案:

答案 0 :(得分:2)

您可以添加排名列,然后按排名过滤结果:

select
    a.kli,
    b.term_desc,
    count(distinct(a.adic)) as count,
    a.partner_id,
    RANK() OVER (PARTITION BY a.partner_id order by a.partner_id DESC) AS r
from
    ad_delivery.sgmt_kli_adic a
    join wand.wandterms b on a.kli = b.term_code
    join wand.wandterms c on b.term_desc=c.term_desc
    join dwh.sgmt_clients e on a.partner_id::varchar = e.partner_id
    join dwh.schema_names f on e.partner_id::integer = f.partner_id::integer
where
    a.partner_id::integer in (f.partner_id)
    and c.class_code = 969
group by a.partner_id, b.term_desc, a.kli
HAVING r < 11
order by partner_id, count desc;

我还没有测试过代码,但是技巧是对GROUP BY的每一行进行排名,并使用HAVING子句过滤结果集,只保留低于11的项目(你会每组获得10项)。