Mariadb:在WHERE子句中使用窗口函数LAG的结果

0wi1tuuw  于 2022-11-23  发布在  其他
关注(0)|答案(2)|浏览(240)

我使用以下查询来获取两个时间戳之间的差异:

SELECT tracker_id,
       TIMESTAMP,
       LAG(TIMESTAMP) OVER(ORDER BY TIMESTAMP DESC),
       TIMESTAMPDIFF(MINUTE,
                     TIMESTAMP,
                     LAG(TIMESTAMP) OVER(ORDER BY TIMESTAMP DESC)) AS diff_in_minutes
  FROM comm_telemetry
 WHERE comm_telemetry.tracker_id = "123456789"
 ORDER BY comm_telemetry.timestamp DESC;

我想过滤结果,只在diff_in_minutes〉0时显示。问题是,WHERE子句中不允许使用窗口函数。
有什么建议怎么这么解决这个?

hfsqlsce

hfsqlsce1#

您将需要首先计算子查询中的滞后时间,然后再次查询该滞后时间以使用它进行筛选。

WITH cte AS (
    SELECT tracker_id,
           TIMESTAMP,
           TIMESTAMPDIFF(MINUTE,
                         TIMESTAMP,
                         LAG(TIMESTAMP) OVER (ORDER BY TIMESTAMP DESC)) AS diff_in_minutes 
    FROM comm_telemetry 
    WHERE tracker_id = '123456789'
)

SELECT tracker_id, TIMESTAMP, diff_in_minutes
FROM cte
WHERE diff_in_minutes > 0
ORDER BY TIMESTAMP DESC;
hjzp0vay

hjzp0vay2#

同时找到了一个解决方案:

WITH tbl_diff_in_minutes AS (SELECT
tracker_id,
`timestamp` as ts,
LAG( `timestamp` ) OVER ( ORDER BY `timestamp` DESC ) prev_ts,
TIMESTAMPDIFF(
    MINUTE,
    `timestamp`,
LAG( `timestamp` ) OVER ( ORDER BY `timestamp` DESC )) AS        diff_in_minutes 
FROM
comm_telemetry 
WHERE
comm_telemetry.tracker_id = "123456789" 
ORDER BY
comm_telemetry.`timestamp` DESC) 

SELECT tracker_id, ts, prev_ts, diff_in_minutes FROM tbl_diff_in_minutes WHERE diff_in_minutes > 0;

相关问题