Sql 研究生:大于第90、95、98百分位的平均值

Sql 研究生:大于第90、95、98百分位的平均值,sql,postgresql,percentile,Sql,Postgresql,Percentile,表中有一列包含多个整数记录 我需要编写一个PostgreSql查询,它将返回大于90%、95%和98%的所有值的平均值 e、 g 我的专栏里有1-150系列 现在,如果我拿这个专栏的第90个百分位,它大约是135 我需要计算所有大于135的值的平均值 同样,对于95%和98%的人群也是如此 如果可能的话,在单个查询中使用所有三个值。作为示例,我使用1到300之间的数字: t=# select generate_series(1,300,1) g g --- 1 2 3 4 ...

表中有一列包含多个整数记录

我需要编写一个PostgreSql查询,它将返回大于90%、95%和98%的所有值的平均值

e、 g

我的专栏里有1-150系列

现在,如果我拿这个专栏的第90个百分位,它大约是135

我需要计算所有大于135的值的平均值

同样,对于95%和98%的人群也是如此


如果可能的话,在单个查询中使用所有三个值。

作为示例,我使用1到300之间的数字:

t=#  select generate_series(1,300,1) g
 g
---
 1
 2
 3
 4
...
下面是一个例子:

t=# with p as (
 with s as (
  select generate_series(1,300,1) g
 )
 select g,ntile(100) over (order by g)
 , case when ntile(100) over (order by g) between 90 and 94 then 90
   when ntile(100) over (order by g) between 95 and 97 then 95
   when ntile(100) over (order by g) >=98 then 98 end "percentile"
 from s
)
select distinct "percentile",avg(g) over (partition by "percentile")
from p
where ntile >=90;
 percentile |         avg
------------+----------------------
         90 | 275.0000000000000000
         98 | 296.0000000000000000
         95 | 287.0000000000000000
(3 rows)

如果我理解正确的话,也许你需要这个

尝试:


您能否添加示例数据和预期输出?
with t(col) as(
    select * from generate_series(1, 150) 
)

select  
    (select avg(col) from t where col > (select count(*) * 90 / 100.00 from t)), 
    (select avg(col) from t where col > (select count(*) * 95 / 100.00 from t)),
    (select avg(col) from t where col > (select count(*) * 98 / 100.00 from t))