How do you show time since the preceding event on each row?

LAG retrieves a prior row from the same window partition. Its default at the first row is NULL.

SQLite example and interpretation

Times two, five and eleven yield missing, three and six seconds. Partition by session before applying this to interleaved sessions.

WITH e(t) AS (VALUES(2),(5),(11)) SELECT t,t-lag(t) OVER(ORDER BY t) FROM e ORDER BY t;

Result [[2, null], [5, 3], [11, 6]]

中文

如何在事件行旁显示距上一次事件的间隔?

LAG 从同一窗口分区取前一行的值,首行没有前驱时默认返回 NULL。

SQLite 示例与适用条件

时间戳 2、5、11 秒得到空、3、6。若混入多个会话,应按会话分区,避免把上次会话尾部算成当前间隔。

WITH e(t) AS (VALUES(2),(5),(11)) SELECT t,t-lag(t) OVER(ORDER BY t) FROM e ORDER BY t;

结果 [[2, null], [5, 3], [11, 6]]

References / 参考来源

Keep reading / 继续阅读