mysql SQL:CAST与window函数结合导致语法错误

7xzttuei  于 12个月前  发布在  Mysql
关注(0)|答案(2)|浏览(143)

我想通过对12个连续值取平均值,将现在包含大量值的数据库压缩到原始大小的1/12。
为此,我使用类型TIMESTAMPFLOAT(4,2)来形成平均值。为了正确地平均TIMESTAMP,我首先想将TIMESTAMP转换为INT,然后用AVG()计算平均值,最后将平均值转换回DATETIME。然而,在此操作期间,我得到了一个语法错误,我无法解释。
这是我尝试过的相应查询:

INSERT INTO condensed_12_current(time_mean, current_mean)
SELECT
  CAST(AVG(CAST(time as INTEGER)) AS DATETIME) OVER (
    ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
  ) AS time_mean,
  AVG(current) OVER (
    ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
  ) AS current_mean
FROM current
WHERE id % 12 = 0;

字符串
造成的错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER)) AS DATETIME) OVER (
    ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
  ' at line 3


我尝试了许多不同版本的CAST指令,但没有一个产生预期的结果。唯一语法正确的CAST语句是当我将AVG()值转换回原始数据类型时。
表current具有以下结构:time as TIMESTAMP current as FLOAT(4,2)id as INT INCREMENT
表condensed_12_current具有以下结构:时间作为TIMESTAMP电流作为FLOAT(4,2)
MYSQL Ver 8.2.0 for Linux on x86_64(MySQL Community Server - GPL)

omqzjyyz

omqzjyyz1#

CAST()不是一个窗口操作,所以我们在看这个表达式时有一个错误:

CAST(AVG(CAST(time as INTEGER)) AS DATETIME) OVER (
    ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
)

字符串
这里,相对于CAST()OVER子句是不正确的。也就是说,你必须转换 * 窗口的整个结果 *。你需要对给定窗口取平均值,而不是对窗口进行转换:

CAST(   AVG(CAST(time as INTEGER)) OVER (
            ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
        )  
    AS DATETIME)

h9vpoimq

h9vpoimq2#

你应该告诉你的数据库如何对行进行排序,否则它将以任意顺序处理它们。例如,按ID列对行进行排序:

avg(current) over (
    order by id rows between 11 preceding and current row
    ) as current_mean

字符串
Example at DB Fiddle
MySQL似乎不支持将timestamp转换为integer。您可以使用from_unixtime()unix_timestamp()来代替:

from_unixtime(avg(unix_timestamp(ts)) over
            (rows between 1 preceding and current row))


Example at DB Fiddle

相关问题