LoginSignup
13
9

More than 5 years have passed since last update.

PostgreSQL で中央値を求める

Posted at

他の RDBMS は知らないが、少なくとも PostgreSQL には MEDIAN という関数は存在しない。
PERCENTILE_CONT を用いて 50 パーセンタイルを求めることで中央値になる。

SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY col)
FROM tbl

パーセンタイルの種類

PostgreSQL のドキュメントを見ると、パーセンタイルにも二種類あるらしい。

PostgreSQL: Documentation: 9.6: Aggregate Functions

continuous percentile: returns a value corresponding to the specified fraction in the ordering, interpolating between adjacent input items if needed

discrete percentile: returns the first input value whose position in the ordering equals or exceeds the specified fraction

例えば中央値を求める際は、データ数が偶数でちょうど真ん中を決められない場合は中央の2つの値の平均をとる。これを continuous percentile と言い、平均を取るのではなく大きい方を選ぶのが discrete percentile と言うらしい。

中央値について調べると「偶数の場合は中央2つの平均を取る」と書いてる事が多いので、continuous percentile を使うほうが正しそう。

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9