加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Postgresql:如何从每个组/类别中选择前n%(%)条目

发布时间:2020-12-13 18:06:09 所属栏目:百科 来源:网络整理
导读:我们是postgres的新手,我们有以下查询,我们可以从中选择每个类别的前N个记录. create table temp ( gp char,val int ); insert into temp values ('A',10); insert into temp values ('A',8); insert into temp values ('A',6); insert into temp values ('A
我们是postgres的新手,我们有以下查询,我们可以从中选择每个类别的前N个记录.
create table temp (
     gp char,val int
 );

 insert into temp values ('A',10);
 insert into temp values ('A',8);
 insert into temp values ('A',6);
 insert into temp values ('A',4);
 insert into temp values ('B',3);
 insert into temp values ('B',2);
 insert into temp values ('B',1);

 select a.gp,a.val
 from   temp a
 where  a.val in (
              select b.val
              from   temp b
              where  a.gp=b.gp
              order by b.val desc
             limit 2);

上述查询的输出是这样的

gp   val
 ----------
 A    10
 A    8
 B    3
 B    2

但是我们的要求是不同的,我们希望从n类未固定的每个类别中选择前n%记录,n基于每个组中元素的百分比.

要根据每个组中行数的百分比检索行,可以使用两个窗口函数:一个用于计算行,另一个用于为它们提供唯一编号.
select gp,val
from (
  select gp,val,count(*) over (partition by gp) as cnt,row_number() over (partition by gp order by val desc) as rn
  from temp
) t
where rn / cnt <= 0.75;

SQLFiddle示例:http://sqlfiddle.com/#!15/94fdd/1

顺便说一句:使用char几乎总是一个坏主意,因为它是一个固定长度的数据类型,填充到定义的长度.我希望你只是为了设置这个例子而做的,不要在你的真实表中使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读