LoginSignup
2
2

More than 5 years have passed since last update.

SELECT文で行(レコード)間の相関係数を取得する

Last updated at Posted at 2013-02-08

example_tb

id a b c d e
1 1 2 3 4 5
2 5 4 3 2 1
3 2 3 4 5 5
4 5 5 4 3 2
5 1 1 1 1 1
6
7 1 2 1 2 1
8 5 4 5 4 5

上記テーブルに対して、id:1のレコードと他のレコードの相関係数を求める

SELECT
x.id, x.a, x.b, x.c, x.d, x.e
(
    (
        (x.a*y.a)+(x.b*y.b)+(x.c*y.c)+(x.d*y.d)+(x.e*y.e) 
    )
    -
    (
        (x.a+x.b+x.c+x.d+x.e)*(y.a+y.b+y.c+y.d+y.e)/5
    )
)
/
NULLIF(
    (
        sqrt(
                (
                    (pow(x.a,2)+pow(x.b,2)+pow(x.c,2)+pow(x.d,2)+pow(x.e,2)) 
                    - 
                    (x.a+x.b+x.c+x.d+x.e)*(x.a+x.b+x.c+x.d+x.e)/5
                )
                *
                (
                    (pow(y.a,2)+pow(y.b,2)+pow(y.c,2)+pow(y.d,2)+pow(y.e,2)) 
                    - 
                    (y.a+y.b+y.c+y.d+y.e)*(y.a+y.b+y.c+y.d+y.e)/5 
                )
            )

    )
,0)
as pearson
from
example_tb x,
example_tb y
where y.id = 1 
order by pearson DESC

詳細は以下にて
http://shimz.me/blog/sql/2564

2
2
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
2
2