我们是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
几乎总是一个坏主意,因为它是固定长度的数据类型,被填充为定义的长度。我希望您只是为了设置示例而已,不要在实际表中使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句