2017-04-19 11 views
0

私は複数の整数レコードを持つテーブルにカラムを持っています。Postgres:90th、95th、98th percentileより大きい値の平均

90,95,98パーセンタイルより大きいすべての値の平均を返すPostgreSQLクエリを書く必要があります。

私はシリーズ1-150を私の列に持っています。私はこのコラムの90パーセンタイルを取る場合

は、今では私も95と98パーセンタイルのために同様に135

より大きいすべての値の平均値を計算する必要が周りに135

です。

可能であれば、すべての3つの値が単一のクエリです。私は1から300までの数字を使用したサンプルとして

+1

あなたがサンプルデータと予想される出力を追加することはできますか? –

答えて

0

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) 
0

私が正しく理解している場合、あなたはこれを必要とするかもしれません。

試してみてください。

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)) 
関連する問題