gpt4 book ai didi

单个字段(最佳拟合线)的MySQL斜率(趋势)

转载 作者:行者123 更新时间:2023-11-29 01:42:52 29 4
gpt4 key购买 nike

我有一个名为 LOGENTRY 的简单表,其中包含名为“DATE”和“COST”的字段。示例:

+--------------+-------+
| DATE | COST |
+--------------+-------+
| MAY 1 2013 | 0.8 |
| SEP 1 2013 | 0.4 |
| NOV 1 2013 | 0.6 |
| DEC 1 2013 | 0.2 |
+--------------+-------+

我想找到 COST 字段随时间的斜率(所选行的范围),结果是SLOPE=-0.00216(相当于 Excel 的 SLOPE 函数,又名线性回归)。

是否有一种简单的方法来选择 COST 的斜率?如果我用调用语言 (php) 进行数学计算,我可以找到斜率:

SLOPE =  (N * Sum_XY - Sum_X * Sum_Y)/(N * Sum_X2 - Sum_X * Sum_X);

我看到了一些类似的问题,但它们更复杂。我试图将这个例子简化为最简单的情况——这样我就能理解答案:)这是我得到的最接近的……但是 MYSQL 提示附近的语法:'float)) AS Sum_X, SUM(CAST(LOGENTRY.DATE as float) * CAST(LOGENTRY.DATE'

SELECT 
COUNT( * ) AS N,
SUM( CAST( LOGENTRY.DATE AS FLOAT ) ) AS Sum_X,
SUM( CAST( LOGENTRY.DATE AS FLOAT ) * CAST( LOGENTRY.DATE AS FLOAT ) ) AS Sum_X2,
SUM( LOGENTRY.COST ) AS Sum_Y, SUM( LOGENTRY.COST * LOGENTRY.COST ) AS Sum_Y2,
SUM( CAST( LOGENTRY.DATE AS FLOAT ) * LOGENTRY.COST ) AS Sum_XY
FROM LOGENTRY

最佳答案

似乎 MySQL 无法将日期转换为 float (根据 stackoverflow 中的其他示例)。也许其他示例引用另一个数据库。因此,通过将日期转换为 unix_timestamps,我能够得到一个答案……用 PHP 进行最终计算。如果这是错误的...请发布,我将删除答案...

SELECT
COUNT(*) AS N,
SUM(UNIX_TIMESTAMP(LOGENTRY.DATE)) AS Sum_X,
SUM(UNIX_TIMESTAMP(LOGENTRY.DATE) * UNIX_TIMESTAMP(LOGENTRY.DATE)) AS Sum_X2,
SUM(LOGENTRY.COST) AS Sum_Y,
SUM(LOGENTRY.COST*LOGENTRY.COST) AS Sum_Y2,
SUM(UNIX_TIMESTAMP(LOGENTRY.DATE) * LOGENTRY.COST) AS Sum_XY
FROM LOGENTRY

关于单个字段(最佳拟合线)的MySQL斜率(趋势),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14899823/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com