我如何根据以下CTE来获取每个CODE的任何两个连续行/ [位置]之间的最大CreateDT差异:
WITH OccDiff AS
(
SELECT
CODE
, CreateDT
, ROW_NUMBER() OVER(PARTITION BY CODE ORDER BY CreateDT DESC) Position FROM Occs
)
我们可以改用LAG / LEAD吗?
SELECT MAX(diff_sec) FROM
(
SELECT
DATEDIFF(
SECOND,
CreateDT,
LEAD(CreateDT) OVER(PARTITION BY CODE ORDER BY CreateDT) --next row's createdt
) as diff_sec
FROM Occs
)x
LEAD将选择相对于当前行的下一个CreateDT(由“具有相同代码的行以及当前行的CreateDT之后在时间上第一个较大的CreateDt”定义的下一个)。 DATEDIFF以秒为单位获取差异(选择合适的时间范围)。它需要包装在子查询中(如果需要,也可以包含CTE),因为窗口函数LEAD不能出现在MAX内]
当然,它可能不是特别有用。.也许也添加代码:
SELECT x.code, MAX(x.diff_sec) FROM
(
SELECT
code,
DATEDIFF(
SECOND,
CreateDT,
LEAD(CreateDT) OVER(PARTITION BY CODE ORDER BY CreateDT) --next row's createdt
) as diff_sec
FROM Occs
)x
GROUP BY x.code