我一直在Postgres中使用新的percentile_cont来计算自发布以来的表的百分位数.但是,我们现在正在更改表格以包含每行的基数,我不确定如何实现percentile_cont以将其考虑在内.
我们之前说这个表看起来像这样:
+--------+--------------+ | name | age | +--------+--------------+ | Joe | 10 | +--------+--------------+ | Bob | 11 | +--------+--------------+ | Lisa | 12 | +--------+--------------+
计算集合中年龄的第85百分位数只需使用:percentile_cont(0.85)WITHIN group(ORDER BY age asc)85
现在,我们为每个名称(具有该特定名称的人数)提供了基数.它看起来像这样:
+--------------+--------+ | name | age | count | +--------+-----+--------+ | Joe | 10 | 2 | +--------+-----+--------+ | Bob | 11 | 1 | +--------+-----+--------+ | Lisa | 12 | 1 | +--------+-----+--------+
有没有办法在Postgres中使用percentile_cont或任何其他内置函数来计算考虑计数/基数的百分位数?
解决方法
最明显的解决方案是根据计数重复行.
示例数据:
create table a_table (name text,age int,count int); insert into a_table values ('Joe',10,3),('Bob',11,2),('Lisa',12,1);
查询:
with recursive data (name,age,count) as ( select * from a_table union all select name,count- 1 from data where count > 1 ) select name,age from data order by 1,2; name | age ------+----- Bob | 11 Bob | 11 Joe | 10 Joe | 10 Joe | 10 Lisa | 12 (6 rows)