Help us understand the problem. What is going on with this article?

PostgreSQL で中央値を求める

More than 1 year has passed since last update.

他の 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 を使うほうが正しそう。

hoto17296
ゆとりデータ分析マン
https://hoto.me/
churadata
沖縄で データ分析 / 機械学習 / Deep Learning をやっている会社です
https://churadata.okinawa/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした