Postgres:select 第 95 个百分位数的所有记录

Postgres: select all records in 95th percentile

我正在尝试查询第 95 个百分位数的所有行。这是我尝试过的。

select
  id,
  percentile_cont(0.95) within group (order by usage asc) as percentile_95
from ResourceUsage
where usage > percentile_95

您的查询失败并显示 ERROR: column "percentile_95" does not exist,这是因为您无法在 SELECT.

WHERE 子句列别名中引用

如果删除 WHERE 子句,则会出现不同的错误

select
  id,
  percentile_cont(0.95) within group (order by usage asc) as percentile_95
from ResourceUsage

ERROR: column "resourceusage.id" must appear in the GROUP BY clause or be used in an aggregate function

指出了如何计算整个 table 的 percentile_cont(即 不使用 使用 GROUP BY):

select
  percentile_cont(0.95) within group (order by usage asc) as percentile_95
from ResourceUsage;

percentile_95             
------------------------- 
95.05 

现在你接近结果了,在子查询中得到上面的结果并在 WHERE 子句中使用它。

select
  id,
  usage
from ResourceUsage
where usage > 
 (select
  percentile_cont(0.95) within group (order by usage asc) as percentile_95
 from ResourceUsage);