我正在尝试计算 MYSQL 表中连续行以及该表中组内的时间戳差异。
数据如下:
"PK" "GROUP" "STEP" "STATUS" "TIMESTAMP" "CORRECT_DIFF"
"1" "1" "1" "N" "13/5/2021 09:00:00" "900"
"2" "1" "2" "A" "13/5/2021 09:15:00" "1800"
"3" "1" "3" "T" "13/5/2021 09:45:00"
"4" "2" "1" "N" "13/5/2021 10:15:00" "2700"
"5" "2" "2" "A" "13/5/2021 11:00:00" "1200"
"6" "2" "3" "T" "13/5/2021 11:20:00"
有第 1 组和第 2 组。在这些组中,可以根据需要设置多个步骤,但上面为每个组显示了 3 个步骤。
我有一个基本查询在工作,但它不尊重分组,我无法弄清楚如何获得它。
这是我目前的查询:
SELECT
A.`TIMESTAMP`,
A.`GROUP`,
A.PK,
TIMESTAMPDIFF( SECOND, A.TIMESTAMP, B.TIMESTAMP ) AS TS_DIFF,
A.CORRECT_DIFF AS TS_DIFF_Correct
FROM
workflow A
INNER JOIN workflow B ON B.PK = A.PK + 1
ORDER BY
PK ASC
哪个给出了正确的值,但也计算了一组与下一组的差异。
如何修改上面的查询,使其只计算组内的连续行差异(上面的 1 或 2)?
也许是一个 MySQL 8 窗口函数?
非常感谢,
答案 0 :(得分:1)
用户LEAD()
:
SELECT wf.*
TIMESTAMPDIFF(SECOND, wf.TIMESTAMP,
LEAD(wf.TIMESTAMP) OVER (PARTITION BY `Group` ORDER BY wf.TIMESTAMP)
) AS TS_DIFF
FROM workflow wf
ORDER BY PK ASC