LAG 和 GROUP BY 在 Maria DB 中不兼容 SQL

LAG and GROUP BY not compatible in Maria DB SQL

我在 MariaDB 中有这个 SQL 查询

  SELECT substr(sqlth_te.tagpath, 32), stringvalue,
    ((t_stamp - (CASE WHEN sqlth_te.tagpath = LAG(sqlth_te.tagpath,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp) Then LAG(t_stamp,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp)
    ELSE NULL
    END))/1000) as seconds
    FROM sqlt_data_1_2022_04
    LEFT JOIN sqlth_te
    ON sqlt_data_1_2022_04.tagid = sqlth_te.id
    WHERE stringvalue IS NOT NULL
    ORDER BY sqlth_te.tagpath, t_stamp

sql code

其中returns 3列;包含机器名称、运行 状态和状态更改后的持续时间的列。

results

我想按机器名称和 运行 状态对持续时间求和,但是当我尝试添加总和并按其分组时出现错误。

SELECT substr(sqlth_te.tagpath, 32), stringvalue,
SUM((t_stamp - (CASE WHEN sqlth_te.tagpath = LAG(sqlth_te.tagpath,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp) Then LAG(t_stamp,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp)
ELSE NULL
END))/1000) as seconds
FROM sqlt_data_1_2022_04
LEFT JOIN sqlth_te
ON sqlt_data_1_2022_04.tagid = sqlth_te.id
WHERE stringvalue IS NOT NULL
ORDER BY sqlth_te.tagpath, t_stamp
GROUP BY substr(sqlth_te.tagpath, 32), stringvalue

错误: java.sql.SQLSyntaxErrorException: (conn=8) 您的 SQL 语法有误;查看与您的 MariaDB 服务器版本对应的手册,了解在第 10

行 'GROUP BY substr(sqlth_te.tagpath, 32), stringvalue' 附近使用的正确语法

知道我做错了什么,或者是否可以对使用滞后函数生成的列进行分组?

谢谢

第一件事:GROUP BY 应该在 ORDER BY

之前

你可能还需要这样嵌套:

SELECT tagpath, stringvalue, SUM(seconds) as seconds
  FROM (
  SELECT substr(sqlth_te.tagpath, 32) as tagpath, stringvalue,
    ((t_stamp - (CASE WHEN sqlth_te.tagpath = LAG(sqlth_te.tagpath,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp) Then LAG(t_stamp,1) OVER (ORDER BY sqlth_te.tagpath, t_stamp)
    ELSE NULL
    END))/1000) as seconds
    FROM sqlt_data_1_2022_04
    LEFT JOIN sqlth_te
    ON sqlt_data_1_2022_04.tagid = sqlth_te.id
    WHERE stringvalue IS NOT NULL
)
GROUP BY tagpath, stringvalue
ORDER BY tagpath, stringvalue