0

我有一个包含数百万条记录的表,其中包含日期/时间戳 - 我正在尝试返回差异 > 给定秒数的记录。

该表包含日期/时间戳,但我无法使用位置和计算出的差异。(createddate 是日期字段,updatedon 是日期/时间)

SELECT createddate,
       LEAD(createddate, 1) OVER (ORDER BY createddate) AS created_next,
       LEAD(createddate, 1) OVER (ORDER BY createddate) - createddate AS created_diff, 
       LEAD(updatedon, 1) OVER (ORDER BY updatedon) AS created_next,
       LEAD(createddate, 1) OVER (ORDER BY updatedon) - updatedon AS Updatedon_diff
FROM   gsdaudit
--WHERE created_diff >  1000
ORDER BY updatedon_diff
4

1 回答 1

1

最简单的方法(假设 SQL 服务器)可能是使用DATEDIFF以秒为单位获取差异并将计算放在公共表表达式中;

WITH cte AS (
  SELECT 
    createddate,
    DATEDIFF(second, createddate, 
             LEAD(createddate, 1) OVER (ORDER BY createddate)) created_diff,
    updatedon,
    DATEDIFF(second, createddate, 
             LEAD(updatedon,   1) OVER (ORDER BY updatedon  )) updatedon_diff
  FROM   gsdaudit
)
SELECT * FROM cte 
WHERE created_diff >  10 OR updatedon_diff > 10

一个用于测试的 SQLfiddle

编辑:Oracle 的相同查询;

WITH cte AS (
  SELECT 
    createddate,
    (LEAD(createddate, 1) OVER (ORDER BY createddate)-createddate)*24*60*60 created_diff,
    updatedon,
    (LEAD(updatedon, 1) OVER (ORDER BY updatedon)-updatedon)*24*60*60 updatedon_diff
  FROM   gsdaudit
)
SELECT * FROM cte 
WHERE created_diff >  10 OR updatedon_diff > 10

另一个 SQLfiddle

于 2013-08-05T15:08:11.830 回答