社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

在MySQL 5中创建关联函数

Tim • 3 年前 • 1763 次点击  

我试图在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

如果得到反馈,我的问题可能会被重新定义为,是否可以将表列作为参数传递给相关函数?如果可以,我如何调整函数以实现这一点?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/162697
文章 [ 2 ]  |  最新文章 3 年前