是否能在 MySQL 查询中计算相关系数?
是的,在查询中计算相关系数是可能的。若要理解查询中的相关系数,需要先创建一个表。创建表的查询如下
mysql> create table correlationDemo - > ( - > value float not null, - > value2 float not null - > ); Query OK, 0 rows affected (0.62 sec)
使用插入命令在表中插入一些记录。在表中插入记录的查询如下
mysql> insert into correlationDemo values(1,10); Query OK, 1 row affected (0.19 sec) mysql> insert into correlationDemo values(2,4); Query OK, 1 row affected (0.16 sec) mysql> insert into correlationDemo values(3,5); Query OK, 1 row affected (0.14 sec) mysql> insert into correlationDemo values(6,17); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from correlationDemo;
以下是输出
+-------+--------+ | value | value2 | +-------+--------+ | 1 | 10 | | 2 | 4 | | 3 | 5 | | 6 | 17 | +-------+--------+ 4 rows in set (0.03 sec)
以下是查询中的简单相关系数
mysql> select @firstValue:=avg(value), - > @secondValue:=avg(value2), - > @division:=(stddev_samp(value) * stddev_samp(value2)) from correlationDemo;
以下是输出
+-------------------------+---------------------------+-------------------------------------------------------+ | @firstValue:=avg(value) | @secondValue:=avg(value2) | @division:=(stddev_samp(value) *stddev_samp(value2)) | +-------------------------+---------------------------+-------------------------------------------------------+ | 3 | 9 | 12.84090685617215 | +-------------------------+---------------------------+-------------------------------------------------------+ 1 row in set (0.00 sec)
以下是上述相关系数查询的计算
mysql> select sum( ( value - @firstValue ) * (value2 - @secondValue) ) / ((count(value) -1) * @division) from - > correlationDemo;
以下是输出
+--------------------------------------------------------------------------------------------+ | sum( ( value - @firstValue ) * (value2 - @secondValue) ) / ((count(value) -1) * @division) | +--------------------------------------------------------------------------------------------+ | 0.7008850777290727 | +--------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
广告