2010-03-16 44 views
8

在MySQL(5.1)數據庫表存在,表示數據:MySQL數學 - 有可能在查詢中計算相關性嗎?

  • 用戶需要多長時間來執行任務,並
  • 用戶在任務期間有多少項目來處理。

MySQL會支持關聯數據還是需要使用PHP/C#來計算?

我在哪裏可以找到一個很好的公式來計算相關性(自從我上次做這件事以來已經很長時間了)?

回答

13

這裏的一個粗略的實施樣品相關係數的如描述:

Wikipedia - Correlation and Dependence

create table sample(x float not null, y float not null); 
insert into sample values (1, 10), (2, 4), (3, 5), (6,17); 

select @ax := avg(x), 
     @ay := avg(y), 
     @div := (stddev_samp(x) * stddev_samp(y)) 
from sample; 

select sum((x - @ax) * (y - @ay))/((count(x) -1) * @div) from sample; 
+---------------------------------------------------------+ 
| sum((x - @ax) * (y - @ay))/((count(x) -1) * @div) | 
+---------------------------------------------------------+ 
|          0.700885077729073 | 
+---------------------------------------------------------+ 
+0

謝謝馬丁。 工程很好 - 我得到了.39的相關性 - 有點弱,但在正確的軌道上。 – 2010-03-18 14:39:35

0

有Pearson相關係數的兩種口味,一個用於樣品,一個用於整個種羣。這些都是單向的,我相信這兩個公式都是正確的:

-- Methods for calculating the two Pearson correlation coefficients 
SELECT 
     -- For Population 
     (avg(x * y) - avg(x) * avg(y))/
     (sqrt(avg(x * x) - avg(x) * avg(x)) * sqrt(avg(y * y) - avg(y) * avg(y))) 
     AS correlation_coefficient_population, 
     -- For Sample 
     (count(*) * sum(x * y) - sum(x) * sum(y))/
     (sqrt(count(*) * sum(x * x) - sum(x) * sum(x)) * sqrt(count(*) * sum(y * y) - sum(y) * sum(y))) 
     AS correlation_coefficient_sample 
    FROM your_table; 

我開發並測試了它作爲T-SQL。生成測試數據的代碼沒有轉換爲MySQL,但公式應該。確保你的x和y是小數值;整數數學可以顯着影響這些計算。