このntile
機能は、ここで非常に役立ちます。私はテーブルを持っていますtest_temp
:
select * from test_temp
score
integer
3
5
2
10
4
8
7
12
select score, ntile(4) over (order by score) as quartile from test_temp;
score quartile
integer integer
2 1
3 1
4 2
5 2
7 3
8 3
10 4
12 4
ntile(4) over (order by score)
列をスコアで並べ替え、4 つの偶数グループに分割し (数値が均等に分割される場合)、順序に基づいてグループ番号を割り当てます。
ここには 8 つの数字があるので、それらは 0、12.5、25、37.5、50、62.5、75、87.5 パーセンタイルを表します。したがって、quartile
が 2 の結果のみを取得すると、25 パーセンタイルと 37.5 パーセンタイルが得られます。
with ranked_test as (
select score, ntile(4) over (order by score) as quartile from temp_test
)
select min(score) from ranked_test
where quartile = 2
group by quartile;
4
8 のリストで 3 番目に大きい を返します。
より大きなテーブルがあり、ntile(100)
フィルター処理する列を使用した場合、パーセンタイルになり、上記と同じクエリを使用できます。