我试图在MySql 5中创建一个相关函数,该函数包含两列(x,y),并返回一个Decimal值(correlation_coefficient)。
这是我的函数定义
-- Calculate pearson correlation coefficient.
-- INPUT: X and Y should be columns of data (decimal)
-- RETURN: A value between -1 and 1 depending on the strength of the relationship between the 2 columns e.g. 0.43.
DELIMITER $$
CREATE FUNCTION PearsonCorrelation(
x Decimal(10,1),
y Decimal(10,1)
)
RETURNS Decimal(10,1)
DETERMINISTIC
BEGIN
DECLARE correlation_coefficient DECIMAL(3,2);
SET correlation_coefficient = (avg(x * y) - avg(x) * avg(y)) / (sqrt(avg(x * x) - avg(x) * avg(x)) * sqrt(avg(y * y) - avg(y) * avg(y)));
RETURN(correlation_coefficient);
END $$
DELIMITER ;
然而,当我执行函数调用时,我会得到错误“组函数的无效使用”。以下是一些测试数据,其中从数据集返回的相关系数应该是
0.86。
CREATE TABLE data_table
(
x Decimal(3,1) NOT NULL,
y Decimal(3,1) NOT NULL
)
INSERT INTO data_table
VALUES(11.2, 10.4),
(9.7, 4.6),
(4.5, 2.1)
我打算将此函数调用如下:
Select PearsonCorrelation(x,y) as corrcoef
FROM data_table
如果得到反馈,我的问题可能会被重新定义为,是否可以将表列作为参数传递给相关函数?如果可以,我如何调整函数以实现这一点?